Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Nginx URL 重寫(Rewrite)完全指南:指令、標記與實戰案例

Nginx 的 rewrite 模組是每一位站長與後端工程師都繞不開的一塊。它把 URI 的改寫能力交到了你手上,也一不小心就會把你帶進 500 錯誤的迴圈裡。本文把常用指令、旗標差異與實戰配置一次講清楚。

Rewrite 模組能做什麼

這個模組允許你使用正則表達式改寫 URI(需要 PCRE 庫支援),並依據相關變量進行重定向或選擇不同的配置。

如果 rewrite 指令寫在 server 區塊中,它會在請求的 location 被確定之前執行;執行完之後,若所選中的 location 裡還有別的重寫規則,那些規則也會被執行。若是在 location 中執行 rewrite 產生了新的 URI,location 會再一次重新匹配新 URI。這個循環最多執行 10 次,超過之後 Nginx 直接回傳 500 錯誤。

break:就地停止後續重寫

語法:break
默認值:無
使用位置:server、location、if

完成當前這組規則設定,並停止執行其他重寫指令。

if ($slow) {
    limit_rate 10k;
    break;
}

if:條件判斷

語法:if (condition) { ... }
默認值:無
使用位置:server、location

官方提醒:使用 if 之前請先讀過 “If is Evil”,並盡量考慮改用 try_files 取代。

判斷一個條件,若成立則執行大括號內的語句,相關配置由上一層繼承。條件可以寫成下列幾種形式:

  • 一個變量名。不成立的值是空字串,或以「0」開頭的字串。
  • 用 = 或 != 的比較運算式。
  • 正則表達式匹配:~ 區分大小寫,~* 不分大小寫(例如 ~* firefox 可匹配 FireFox),!~ 與 !~* 表示「不匹配」。
  • -f 與 !-f 檢查檔案是否存在;-d 與 !-d 檢查目錄;-e 與 !-e 檢查檔案、目錄或軟連結;-x 與 !-x 檢查是否為可執行檔。
  • 正則中的部分可以用圓括號圈起來,之後依序以 $1 到 $9 引用。

常見寫法示例:

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
}

if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
}

if ($request_method = POST) {
    return 405;
}

if (!-f $request_filename) {
    break;
    proxy_pass https://127.0.0.1;
}

if ($slow) {
    limit_rate 10k;
}

if ($invalid_referer) {
    return 403;
}

if ($args ~ post=140) {
    rewrite ^ https://example.com/ permanent;
}

其中內建變量 $invalid_referer 由 valid_referers 指令指定。

return:直接回傳狀態碼

語法:return code
使用位置:server、location、if

結束執行後續配置語句並向客戶端回傳狀態碼,可用的值有 204、400、402~406、408、410、411、413、416 與 500~504。另外還有一個非標準碼 444,它會直接關閉連接且不送出任何標頭。

rewrite:核心指令與四個旗標

語法:rewrite regex replacement flag
使用位置:server、location、if

依據正則表達式修改 URI,指令按配置檔中出現的順序執行。如果替換字串以 https:// 開頭,請求會被重定向,且不再執行多餘的 rewrite。

尾部的旗標有四種,理解它們的差異是關鍵:

  • last:完成重寫,之後重新搜尋對應的 URI 或 location。
  • break:完成重寫,就此停下。
  • redirect:回傳 302 臨時重定向(替換欄位以 https:// 開頭時使用)。
  • permanent:回傳 301 永久重定向。

若重定向是相對路徑(沒有主機名部分),Nginx 會使用匹配 server_name 的「Host」標頭,或 server_name 指定的第一個名稱;標頭不匹配或不存在時退回本地主機名。若你總希望使用 Host 標頭,可以在 server_name 中使用 * 萬用字元。

rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra last;
return 403;

但如果把上面這段放進名為 /download/ 的 location 裡,就必須把 last 改成 break,否則 Nginx 會陷入 10 次循環並回傳 500。

location /download/ {
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra break;
    return 403;
}

參數、括號與引號的三個細節

附加參數:若替換欄位中含有參數,其餘的請求參數會被附加在後面。若要阻止附加,在最後一個字元後補上一個問號:

rewrite ^/users/(.*)$ /show?user=$1? last;

大括號衝突:大括號 { } 同時用於正則表達式與配置區塊,為避免衝突,含大括號的正則必須用雙引號或單引號包起來。例如把 /photos/123456 改寫成 /path/to/photos/12/1234/123456.png:

rewrite "/photos/([0-9]{2})([0-9]{2})([0-9]{2})" /path/to/photos/$1/$1$2/$1$2$3.png;

丟棄參數:在 rewrite 結尾加上 ?,Nginx 會丟掉請求中的參數(即 $args)。當你使用 $request_uri 或 $uri&$args 時,用這招可以避免 Nginx 重複處理參數串。

用 $request_uri 做網域導向

server {
    server_name www.example.com;
    rewrite ^ https://example.com$request_uri? permanent;
}

要注意,rewrite 只對路徑操作,不處理參數。若需要改寫帶參數的 URL,改用 if 判斷:

if ($args ~ post=100) {
    rewrite ^ https://example.com/new-address.html? permanent;
}

另外,$args 變量不會被編譯,這與 location 處理過程中的 URI 不同。

其他輔助指令

rewrite_log 語法:rewrite_log on | off,默認 off,可用於 server、location、if。開啟後會在 error log 中記錄 notice 等級的重寫日誌。

set 語法:set variable value,可用於 server、location、if。為變量賦值,值可以是文字、變量或兩者的組合。你可以用 set 定義新變量,但不能用它設定 $http_xxx 標頭變量。

uninitialized_variable_warn 語法:uninitialized_variable_warn on | off,默認 on,可用於 http、server、location、if。控制是否在未初始化變量時記錄警告日誌。

rewrite 背後的堆疊虛擬機

rewrite 指令其實在配置檔載入時就已被編譯成內部碼,請求到來時由直譯器執行。這個直譯器是一個簡單的堆疊虛擬機。例如:

location /download/ {
    if ($forbidden) { return 403; }
    if ($slow) { limit_rate 10k; }
    rewrite ^/(download/.*)/media/(.*)\..*$ /$1/mp3/$2.mp3 break;
}

會被編譯成類似下面的順序:

variable $forbidden checking to zero
recovery 403
completion of entire code
variable $slow checking to zero
checking of regular expression
copying "/"
copying $1
copying "/mp3/"
copying $2
copying ".mp3"
completion of regular expression
completion of entire sequence

注意其中並沒有 limit_rate 的相關碼,因為它屬於另一個模組。如果 $slow 為真,對應的 if 區塊會生效,此例中 limit_rate 為 10k。

如果我們把第一個斜線也括入圓括號,複製步驟會更少:

rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;

編譯後只剩「檢查正則 → 複製 $1 → 複製 /mp3/ → 複製 $2 → 複製 .mp3 → 結束」。

實戰一:跨主機臨時重定向(302)

先備份原配置,另開一份乾淨的配置檔,避免大量註解干擾閱讀:

[root@nginx ~]# cd /etc/nginx/
[root@nginx nginx]# mv nginx.conf nginx.conf.proxy
[root@nginx nginx]# cp nginx.conf.bak nginx.conf
[root@nginx nginx]# vim /etc/nginx/nginx.conf
server {
    listen 80;
    server_name localhost;

    location / {
        root html;
        index index.html index.htm;
        rewrite ^/bbs/(.*)$ https://192.168.18.201/forum/$1;
    }
}

在目標主機上準備 forum 目錄與測試頁:

[root@web1 ~]# cd /var/www/html/
[root@web1 html]# mkdir forum
[root@web1 html]# cd forum/
[root@web1 forum]# vim index.html
forum page!

測試前先確認頁面本身可訪問:

Nginx URL 重寫(Rewrite)完全指南:指令、標記與實戰案例

重新載入配置:

[root@nginx 63]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重新載入 nginx: [確定]

再測一次:

Nginx URL 重寫(Rewrite)完全指南:指令、標記與實戰案例

圖中的 status code 是 302,代表臨時重定向,說明 rewrite 已經生效。一般來說,伺服器與伺服器之間用臨時重定向,伺服器內部則用永久重定向。

實戰二:本機永久重定向(301)

[root@nginx nginx]# vim /etc/nginx/nginx.conf
server {
    listen 80;
    server_name localhost;

    location / {
        root html;
        index index.html index.htm;
        rewrite ^/bbs/(.*)$ /forum/$1;
    }
}
[root@nginx ~]# cd /usr/html/
[root@nginx html]# mkdir forum
[root@nginx html]# cd forum/
[root@nginx forum]# vim index.html
192.168.18.208 forum page

重新載入後測試:

[root@nginx ~]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重新載入 nginx: [確定]
Nginx URL 重寫(Rewrite)完全指南:指令、標記與實戰案例

可以看到訪問 /bbs/ 會被直接跳轉到 /forum/,這種本機跳轉就是永久重定向,也稱隱式重定向。

更多重定向相關指令,建議直接查閱 Nginx 官方文檔;在複雜場景下,優先考慮用 try_files 取代層層堆疊的 if。

Copyright © Linux教程網 All Rights Reserved