Nginx 作為高性能 Web 服務器,提供了兩種截然不同的緩存機制:proxy_cache 與 fastcgi_cache。理解它們的適用場景對優化 PHP 應用性能至關重要。
| 特性 | proxy_cache | fastcgi_cache |
|---|---|---|
| 緩存對象 | 後端服務器返回的完整 HTTP 響應(靜態/動態均可) | FastCGI 進程生成的內容(通常為 PHP 動態輸出) |
| 通信層級 | HTTP 協議層(Nginx ↔ 上游 HTTP 服務) | FastCGI 協議層(Nginx ↔ PHP-FPM) |
| 主要收益 | 減少 Nginx 與後端 HTTP 交互,節省網絡帶寬 | 減少 Nginx 與 PHP-FPM 交互,降低 PHP 解析與數據庫壓力 |
| 典型場景 | 反向代理、負載均衡、微服務網關 | PHP 應用加速(WordPress、Laravel、ThinkPHP 等) |
# 定義緩存路徑與參數(必須在 http 塊中)
proxy_temp_path /data0/proxy_temp_dir;
proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
server {
listen 80;
server_name www.example.com;
location / {
# 故障轉移:遇到 502/504/超時自動切換上游
proxy_next_upstream http_502 http_504 error timeout invalid_header;
# 啟用緩存區
proxy_cache cache_one;
# 狀態碼緩存策略
proxy_cache_valid 200 304 12h;
proxy_cache_valid 301 302 1h;
proxy_cache_valid any 1m;
# 緩存 Key 構建(域名 + URI + 參數)
proxy_cache_key $host$uri$is_args$args;
# 透傳必要 Header
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass https://backend_server;
expires 1d;
}
# 手動清理緩存接口(僅允許內網 IP)
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.0.0/16;
deny all;
proxy_cache_purge cache_one $host$1$is_args$args;
}
# 動態腳本不緩存
location ~ \.(php|jsp|cgi)$ {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass https://backend_server;
}
}
# http 塊中定義緩存區
fastcgi_cache_path /tt/cache levels=1:2 keys_zone=NAME:2880m inactive=2d max_size=10G;
fastcgi_cache_key "$scheme$request_method$host$uri$arg_filename$arg_x$arg_y";
server {
listen 8080;
server_name www.example.com;
location / {
root /www;
index index.html index.htm index.php;
}
location ~ \.php$ {
root /www;
fastcgi_pass 127.0.0.1:9000;
# 啟用 fastcgi 緩存
fastcgi_cache NAME;
fastcgi_cache_valid 200 48h;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi.conf;
# 關鍵:允許傳遞 Set-Cookie 防止緩存會話污染
fastcgi_pass_header Set-Cookie;
}
}
除了 Nginx 層面,應用層緩存同樣關鍵:
fastcgi_cache,配合 fastcgi_cache_bypass、fastcgi_no_cache 跳過登錄用戶/POST 請求。proxy_cache 緩存下游服務響應。inactive、max_size,結合 Lua 腳本實現緩存預熱與熔斷。合理組合 Nginx 雙層緩存與應用層緩存,可將 PHP 應用吞吐量提升 10-100 倍,是高併發架構的基石。