[Nginx] 在 abc.com/abc/def.htm 這個特定網址導向(rewrite) subdomain cba.def, 其餘參數不變


location ~ /abc/def.htm(.*)$ {
   rewrite ^/(.*) http://cba.def/$1 permanent;
}

location ~ // 使用正規表達式,有視大小寫
location ~* // 代表使用正規表達式,忽視大小寫
# 當路徑符合 /test/js/test.js 無視後面帶什麼參數時,進去裡面
location ~* /test/js/test.js(.*)$ {
    # 檢查如果你進來的網址是 /test/js/test.js
    # 後面帶的參數會被 /test/js/test.js(.*) 的 (.*) 捕捉到 $1 
    # 然後將流量導向 /test/js/test.php
    # 並將後面帶的所有東西也補在 /test/js/test.php 後
    rewrite ^/test/js/test.js(.*) /test/js/test.php$1 last;
}
location 中的 rewirte:
不寫last和break - 那麼流程就是依次執行這些rewrite
1. rewrite break - url重寫後,直接使用當前資源,不再執行 location 裡面剩下的語句,完成本次請求,地址欄url不變
2. rewrite last - url重寫後,馬上發起一個新的請求,再次進入server塊,重試location匹配,超過10次匹配不到報500錯誤,地址欄url不變
3. rewrite redirect – 返回302臨時重定向,地址欄顯示重定向後的url,爬蟲不會更新url(因為是臨時)
4. rewrite permanent – 返回301永久重定向, 地址欄顯示重定向後的url,爬蟲更新url

使用last會對server標籤重新發起請求
如果location中rewrite後是對靜態資源的請求,不需要再進行其他匹配,一般要使用break或不寫,直接使用當前location中的數據源,完成本次請求
如果location中rewrite後,還需要進行其他處理,如動態fastcgi請求(.php,.jsp)等,要用last繼續發起新的請求
(根的location使用last比較好, 因為如果有.php等fastcgi請求還要繼續處理)

留言

這個網誌中的熱門文章

[翻譯] 介紹現代網路負載平衡與代理伺服器

Grafana K6

Linux 事件驅動筆記