Nginx 提供兩種核心快取機制,針對不同架構層級優化效能:
| 特性 | proxy_cache | fastcgi_cache |
|---|---|---|
| 快取對象 | 後端伺服器回應(靜態/動態皆可) | FastCGI 進程產生的內容(通常為 PHP 動態頁) |
| 減少通訊 | Nginx ↔ 後端伺服器 | Nginx ↔ PHP-FPM |
| 壓力分擔 | 後端帶寬、傳輸時間 | PHP 處理、資料庫查詢 |
| 適用場景 | 反向代理、負載均衡架構 | PHP 應用直接掛載於 Nginx |
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 / {
proxy_cache cache_one;
proxy_cache_valid 200 304 12h;
proxy_cache_key $host$uri$is_args$args;
proxy_pass https://backend_server;
proxy_next_upstream http_502 http_504 error timeout invalid_header;
}
# 快取清除端點
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_pass https://backend_server; }
}
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;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_cache NAME;
fastcgi_cache_valid 200 48h;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_pass_header Set-Cookie; # 關鍵:允許 Cookie 穿透
include fastcgi.conf;
}
}
levels=1:2:二級目錄結構,避免單目錄檔案過多keys_zone:共享記憶體區名稱與大小(存放快取索引)inactive:未被存取多久刪除max_size:磁碟快取上限,超過自動淘汰 LRUfastcgi_pass_header Set-Cookie:解決快取導致 Cookie 無法寫入的關鍵兩種快取可同時啟用(如 CDN → Nginx proxy_cache → PHP fastcgi_cache),按需分層部署。