Nginx 負責靜態資源與反向代理,PHP 透過 php-cgi.exe 以 FastCGI 模式運行(監聽 127.0.0.1:9000)。Nginx 遇到 .php 請求轉發給 FastCGI 處理。
nginx-1.5.2(或較新穩定版)php-5.4.3 (Non Thread Safe 版本,含 php-cgi.exe)RunHiddenConsole.exe(讓 FastCGI 背景執行不佔用視窗)全部解壓至 D:\webServer\ 目錄:
D:\webServer\nginx-1.5.2\
D:\webServer\php-5.4.3\
conf/nginx.confserver {
listen 80;
server_name localhost;
charset utf-8;
# 靜態資源根目錄
location / {
root E:/work/jentian/client;
index index.html index.htm;
}
# PHP 處理
location ~ \.php$ {
root E:/work/jentian/server; # PHP 檔案實體路徑
fastcgi_param SCRIPT_FILENAME E:/work/jentian/server$fastcgi_script_name;
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
}
}
關鍵:fastcgi_param SCRIPT_FILENAME 路徑必須與 root 指向一致,否則 PHP 會找不到腳本檔案。
php.ini; 必須啟用
cgi.fix_pathinfo=1
; 擴充模組依專案需求啟用
extension_dir = "ext"
extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_pdo_mysql.dll
; 時區
date.timezone = Asia/Taipei
start_nginx_php.bat@echo off
set PHP_FCGI_MAX_REQUESTS=1000
echo 啟動 PHP FastCGI...
RunHiddenConsole D:\webServer\php-5.4.3\php-cgi.exe -b 127.0.0.1:9000 -c D:\webServer\php-5.4.3\php.ini
echo 啟動 Nginx...
D:\webServer\nginx-1.5.2\nginx.exe -p D:\webServer\nginx-1.5.2\
cd /d D:\webServer\nginx-1.5.2\
pause
RunHiddenConsole 讓 php-cgi 在背景執行,關閉 CMD 視窗不會終止進程。
stop_nginx_php.bat@echo off
echo 停止 Nginx...
D:\webServer\nginx-1.5.2\nginx.exe -s quit
echo 停止 PHP FastCGI...
taskkill /f /im php-cgi.exe >nul 2>&1
pause
start_nginx_php.bat。https://localhost/ → 應顯示 Nginx 歡迎頁。E:/work/jentian/server 建立 info.php:<?php phpinfo(); ?>。https://localhost/info.php → 應顯示 PHP 資訊頁。| 現象 | 可能原因 | 解決 |
|---|---|---|
| PHP 頁面顯示原始碼 | FastCGI 未啟動或 port 錯誤 | 檢查 9000 port、php-cgi 進程、防火牆 |
| 404 No input file specified | SCRIPT_FILENAME 路徑錯誤 | 確認 root 與 fastcgi_param 路徑一致 |
| 502 Bad Gateway | php-cgi 崩潰或超時 | 查 php 錯誤日誌、調大 request_terminate_timeout |