萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Windows 7 環境建置 Nginx + PHP + MySQL 完整教學

本教學示範在 Windows 7 上以手動方式建置 Nginx、PHP (FastCGI)、MySQL 開發環境。

軟體版本

  • Nginx:nginx-1.1.7.zip
  • PHP:php-5.3.6-nts-Win32-VC9-x86.zip (Non Thread Safe 版)
  • MySQL:mysql-essential-5.1.57-win32.msi
  • 輔助工具:RunHiddenConsole.exe (讓 FastCGI 在背景執行)

安裝步驟

1. MySQL

解壓安裝至 F:\WAMP\MySQL,依精靈完成設定 (root 密碼、Port 3306、啟用網路)。

2. Nginx

解壓至 F:\WAMP\Nginx。雙擊 nginx.exe,工作管理員可見 nginx.exe 進程。瀏覽 https://localhost/ 應顯示「Welcome to nginx!」。

3. PHP

解壓至 F:\WAMP\PHP。將 php.ini-development 複製為 php.ini 並編輯:

; 擴展目錄
extension_dir = "F:/WAMP/PHP/ext"

; 啟用常用擴展
extension=php_mbstring.dll
extension=php_gd2.dll
extension=php_mysql.dll
extension=php_pdo_mysql.dll

; 文件根目錄 (對應 Nginx root)
doc_root = "F:/WAMP/www"

; CGI/FastCGI 關鍵設定
cgi.force_redirect = 0
cgi.fix_pathinfo = 1
fastcgi.impersonate = 1
cgi.rfc2616_headers = 1

; 時區
date.timezone = Asia/Taipei

Nginx 設定 (nginx.conf)

location / {
    root F:/WAMP/www;
    index index.html index.htm index.php;
    autoindex on;
}

location ~ \.php$ {
    root F:/WAMP/www;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME F:/WAMP/www$fastcgi_script_name;
    include fastcgi_params;
}

關鍵點:fastcgi_pass 埠號 (9000) 必須與 PHP FastCGI 啟動參數一致;SCRIPT_FILENAME 必須指向實體檔案完整路徑。

啟動與停止腳本

啟動 PHP FastCGI (start_php.bat)

@echo off
echo Starting PHP FastCGI...
RunHiddenConsole.exe F:\WAMP\PHP\php-cgi.exe -b 127.0.0.1:9000 -c F:\WAMP\PHP\php.ini

停止服務 (stop_all.bat)

@echo off
echo Stopping nginx...
taskkill /F /IM nginx.exe > nul
echo Stopping PHP FastCGI...
taskkill /F /IM php-cgi.exe > nul
exit

驗證

  1. 執行 start_php.bat
  2. 雙擊 nginx.exe
  3. 在 F:\WAMP\www 建立 index.php:<?php phpinfo(); ?>
  4. 瀏覽 https://localhost/index.php 應顯示 PHP 資訊頁,且 MySQL 區塊顯示已啟用

常見問題

  • PHP 無法載入擴展:檢查 extension_dir 路徑、php.ini 是否被系統讀取 (可複製至 C:\Windows 測試)
  • Nginx 502 Bad Gateway:PHP FastCGI 未啟動或埠號不符
  • 中文亂碼:確認資料庫、表、連線、PHP mbstring.internal_encoding 皆為 UTF-8
copyright © 萬盛學電腦網 all rights reserved