Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Nginx + PHP (FastCGI) 高效能 Web 伺服器完整建置實戰:從原始碼編譯到多站點配置

編輯:關於伺服器

環境與版本資訊

  • OS:CentOS 4.7 (Kernel 2.6.9)
  • Nginx 0.6.35、PHP 5.2.9 (php-fpm 0.5.10)、MySQL 5.1.34
  • 依賴庫:libiconv、libmcrypt、mhash、mcrypt

編譯安裝流程概覽

  1. 依賴庫: libiconv → libmcrypt → mhash → mcrypt(順序不可亂)
  2. MySQL: 建立 mysql 用戶/群組,編譯參數啟用 InnoDB、SSL、大表支援
  3. PHP (FastCGI/FPM): 打入 php-fpm patch,啟用 --enable-fpm、--with-mysql、--with-gd、--with-openssl 等
  4. php-fpm 配置: XML 格式,設定 pid、錯誤日誌、進程池 (static, max_children=128)、慢查詢日誌、rlimit_files=51200
  5. 建立 www 用戶/群組 對應 php-fpm worker 身分
  6. Nginx: 編譯參數 --user=www --group=www --with-http_ssl_module --with-http_stub_status_module
  7. 建立 fcgi.conf 定義 FastCGI 參數(SCRIPT_FILENAME 等)
  8. Nginx 主配置: worker_processes 8、epoll、51200 connections、gzip、多 server 區塊支援多域名、FastCGI 連接 127.0.0.1:9000
  9. 開機自啟: /etc/rc.local 加入 ulimit、php-fpm start、nginx
  10. 核心參數優化: /etc/sysctl.conf 調整 tcp_fin_timeout、tcp_tw_reuse/recycle、syncookies 等

關鍵配置片段

Nginx 多站點範例

server {
    listen 80;
    server_name www.example.com;
    root /usr/local/webserver/nginx/html/www.example.com;
    index index.php index.html;

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fcgi.conf;
    }
    location ~* \.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; }
    location ~* \.(js|css)$ { expires 6h; }
    access_log logs/example.log combined;
}

平滑重啟指令

# Nginx
kill -HUP `cat /usr/local/webserver/nginx/logs/nginx.pid`

# PHP-FPM
/usr/local/webserver/php/sbin/php-fpm restart

驗證與常見坑點

  • 瀏覽 https://IP/test.php 應顯示 phpinfo() 頁面
  • 若出現 502 Bad Gateway,檢查 php-fpm 是否運行、9000 埠是否監聽、防火牆規則、fcgi.conf 中 SCRIPT_FILENAME 路徑是否正確
  • 靜態檔案 404:確認 root 指向正確、index 指令包含 index.php
  • 權限問題:網站目錄擁有者需為 www:www,目錄 755、檔案 644

結語

本文記錄的編譯參數與配置經實測可穩定運行,適用於中小型高併發 Web 服務。生產環境建議升級至 Nginx 1.x/OpenResty、PHP 7.x/8.x、MariaDB 10.x 並引入監控(Prometheus+Grafana)與自動化部署(Ansible/Docker)。

Copyright © Windows教程網 All Rights Reserved