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

Nginx + PHP-FPM 檔案上傳失效完整排查指南:從 client_max_body_size 到 php.ini 核心參數

編輯:關於伺服器

Nginx + PHP-FPM 架構下檔案上傳失敗,常見癥狀為「413 Request Entity Too Large」、「POST 請求大小限制」或上傳後檔案為 0 字節。根因通常涉及 Nginx、PHP-FPM、PHP 三層限制疊加。本文提供系統性排查清單與標準化配置模板。

三層限制架構圖

客戶端請求
    │
    ▼
Nginx (client_max_body_size, client_body_temp_path)
    │
    ▼
PHP-FPM (fastcgi_request_buffering, fastcgi_max_temp_file_size)
    │
    ▼
PHP 核心 (upload_max_filesize, post_max_size, memory_limit, max_execution_time, max_input_time)

Nginx 層配置 (關鍵)

location ~ \.php$ {
    root /var/www/html/public;
    client_max_body_size 50M;          # 允許最大請求體,預設 1M
    client_body_temp_path /tmp;           # 上傳臨時目錄,必須 PHP-FPM 進程用戶可寫
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

注意: 若啟用 fastcgi_request_buffering off;,大檔直接寫入磁臨時檔,減少記憶體壓力,但需確保 client_body_temp_path 分區空間充足。

PHP-FPM 層配置 (php-fpm.conf / www.conf)

; 允許單次請求最大緩衝 (預設 1M,建議與 client_max_body_size 一致)
request_terminate_timeout = 300
; 大檔案上傳建議關閉請求緩衝,直接落盤
fastcgi_request_buffering = off
fastcgi_max_temp_file_size = 100M

PHP 核心層配置 (php.ini 生產建議值)

參數建議值說明
file_uploadsOn總開關
upload_max_filesize100M單檔上限
post_max_size110M必須 > upload_max_filesize,含表單其他欄位
max_execution_time300腳本最大執行秒數,大檔上傳需放寬
max_input_time300接收 POST/GET/PUT 數據最大秒數
memory_limit256M單腳本記憶體上限,≥ post_max_size
upload_tmp_dir/tmp臨時目錄,確保 PHP-FPM 用戶可寫、空間足夠、權限 1777

排查檢查清單 (由外而內)

  1. Nginx error.log 搜尋 client intended to send too large body → 調大 client_max_body_size。
  2. PHP-FPM log 搜尋 request_terminate_timeout 或 fastcgi_request_buffering 相關錯誤。
  3. PHP 錯誤日誌 搜尋 POST Content-Length of xxx bytes exceeds the limit → 調大 post_max_size。
  4. 瀏覽器開發者工具 Network 面板:查看 Request Payload 大小、Response 狀態碼 (413/500/200)。
  5. 權限檢查:ls -ld /tmp 確認 drwxrwxrwt;PHP-FPM 進程用戶 (通常 www-data) 能在該目錄建檔。
  6. 磁碟空間:df -h /tmp 確保臨時分區剩餘 > 上傳檔案大小 2 倍。

常見誤區

  • 只改 upload_max_filesize 不改 post_max_size → 仍報 413。
  • memory_limit 小於 post_max_size → 大檔處理時 OOM。
  • 修改 php.ini 後未重載 PHP-FPM (systemctl reload php-fpm)。
  • Nginx client_body_temp_path 指向無寫權限目錄 → 上傳靜默失敗或 500。

依「桶理論」逐層放寬限制,並確保臨時目錄權限與空間,即可徹底解決 Nginx + PHP-FPM 上傳難題。

Copyright © Windows教程網 All Rights Reserved