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

Nginx try_files 指令詳解與 WordPress Super Cache 實戰應用

編輯:Linux 教學

Nginx 0.6.36 版本引入的 try_files 指令,能依序檢查多個檔案是否存在,若皆不存在則導向 fallback 處理。這項功能可大幅簡化 rewrite 規則,尤其適合 WordPress 靜態快取(如 WP Super Cache)的 Nginx 設定。

一、try_files 語法與運作原理

try_files file1 [file2 ... filen] fallback;
  • 作用域:location 區塊
  • 運作邏輯:依序嘗試 file1、file2…,找到即回應;全部找不到則轉向 fallback(可為命名 location 或 URI)。

二、基礎範例

location / {
    try_files index.html index.htm @fallback;
}

location @fallback {
    root /var/www/error;
    index index.html;
}

若網站根目錄下無 index.html 或 index.htm,請求會導向 @fallback 由錯誤頁面處理。

三、WordPress Super Cache 完整設定範例

以下為作者實測可用的 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;
    }
}

四、關鍵點說明

  1. $cache/$uri/index.html.gz 對應 WP Super Cache 的目錄結構。
  2. add_header Content-Encoding "gzip" 告訴瀏覽器內容已壓縮,Nginx 不再重複壓縮。
  3. 靜態檔案區塊獨立設定 expires 30d 並啟用 gzip,減少後端負載。
  4. @proxy 為命名 location,避免與一般 location 衝突。

善用 try_files 即可讓 Nginx 以極簡單的邏輯實現「靜態優先、動態備援」的高效能架構。

Copyright © Windows教程網 All Rights Reserved