萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Nginx + PHP-FPM 架構下 WordPress 502 Bad Gateway 完整排查方案

現象

WordPress 站點頻繁出現 502 Bad Gateway,錯誤日誌常見:

upstream sent too big header while reading response header from upstream

核心調優方向

  1. PHP-FPM 進程數與超時
  2. Nginx FastCGI 緩衝區大小
  3. Proxy 代理緩衝區(反向代理場景)
  4. PHP 執行時間與 Nginx 等待逾時

具體配置調整

1. PHP-FPM 設定(/usr/local/php/etc/php-fpm.conf 或 /www/wdlinux/php/etc/php-fpm.conf)

pm.max_children = 30          ; 原 10,視記憶體調整
request_terminate_timeout = 60s ; 原 0,防止進程長期掛起

2. Nginx FastCGI 緩衝區(nginx.conf http 區塊)

fastcgi_buffers 8 128k;
fastcgi_buffer_size 128k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;

若日誌仍報 too big header,可嘗試:

fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;

3. 反向代理緩衝區(若 Nginx 做 Proxy)

server {
    listen 80;
    server_name *.example.com;
    location / {
        proxy_buffer_size 64k;
        proxy_buffers 32 32k;
        proxy_busy_buffers_size 128k;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # ...
    }
}

4. PHP 執行逾時(php.ini)

max_execution_time = 300

其他常見原因快速檢查

  • php-cgi 進程數不足:同上調大 max_children,注意記憶體上限。
  • max_requests 過小:導致進程頻繁回收,適當增大。
  • Nginx 錯誤日誌路徑:/var/log/nginx/error.log,務必以此為依據定位具體原因。

總結檢查清單

層面關鍵參數建議值
PHP-FPMpm.max_children30~100(視 RAM)
PHP-FPMrequest_terminate_timeout60s
Nginx FastCGIfastcgi_buffers / buffer_size8 128k / 128k
Nginx FastCGIfastcgi_*_timeout300
Proxyproxy_buffers / buffer_size32 32k / 64k
PHPmax_execution_time300

依序調整並觀察日誌,多數 502 可徹底解決。

copyright © 萬盛學電腦網 all rights reserved