Nginx 0.6.36 版本引入的 try_files 指令,能依序檢查多個檔案是否存在,若皆不存在則導向 fallback 處理。這項功能可大幅簡化 rewrite 規則,尤其適合 WordPress 靜態快取(如 WP Super Cache)的 Nginx 設定。
try_files file1 [file2 ... filen] fallback;
location / {
try_files index.html index.htm @fallback;
}
location @fallback {
root /var/www/error;
index index.html;
}
若網站根目錄下無 index.html 或 index.htm,請求會導向 @fallback 由錯誤頁面處理。
以下為作者實測可用的 Nginx 設定,直接讀取 WP Super Cache 產生的 .html.gz 靜態檔,找不到才轉給後端 Apache(或 PHP-FPM)動態處理:
server {
listen 80;
server_name _;
set $cache /wp-content/cache/supercache/$host;
location / {
root /home/html/s0001/domains/$host;
index index.php index.html;
# 直接輸出 gzip 壓縮後的靜態 HTML
add_header Content-Type "text/html; charset=UTF-8";
add_header Content-Encoding "gzip";
try_files $cache/$uri/index.html.gz @proxy;
}
# 靜態資源由 Nginx 直接服務並啟用 gzip
location ~* \.(jpg|jpeg|png|gif|css|js|swf|mp3|avi|flv|xml|zip|rar)$ {
expires 30d;
gzip on;
gzip_types text/plain application/x-javascript text/css application/xml;
root /home/html/s0001/domains/$host;
}
# 找不到快取檔,轉給後端 Apache (port 8080)
location @proxy {
index index.php index.htm index.html;
root /home/html/$user/domains/$host;
proxy_pass https://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
$cache/$uri/index.html.gz 對應 WP Super Cache 的目錄結構。add_header Content-Encoding "gzip" 告訴瀏覽器內容已壓縮,Nginx 不再重複壓縮。expires 30d 並啟用 gzip,減少後端負載。@proxy 為命名 location,避免與一般 location 衝突。善用 try_files 即可讓 Nginx 以極簡單的邏輯實現「靜態優先、動態備援」的高效能架構。