今天在配置nginx轉發的時候遇到了一個問題:proxy_pass路徑末尾加不加 / 差別很大。下邊兩種配置跳轉的路徑是不一樣的。
# nginx配置
server {
listen 8088;
server_name localhost;
location ^~ /test/ {
proxy_pass http://localhost:8000/; # 帶 /
}
location ^~ /test/ {
proxy_pass http://localhost:8000; # 不帶 /
}
}
在任意目錄下運行 puer
(啟動一個文件服務器,默認8000端口,nginx上邊的配置會代理過來)
# 文件服務器根目錄
├── test
│ ├── index.html
├── index.html
├── rewrite
├── ├── index.html
我們在瀏覽器中輸入 http://localhost/test/index.html
- 帶/實際訪問的是
http://localhost:8000/index.html
(相當於根或絕對路徑,不會在代理路徑后拼接locaiton中匹配規則的路徑,比如上邊的test
) - 無/實際訪問的是
http://localhost:8000/test/index.html
(相當於相對路徑,會在代理路徑后拼接locaiton中匹配規則的路徑)
當然,我們可以使用 rewrite
來實現 proxy_pass后加 / 的效果
# 實際訪問的是 `http://localhost:8000/index.html`
location ^~ /test/ {
rewrite /test/(.+)$ /$1 last;
}
同樣我們也可以改為如下:
# 實際訪問的是 `http://localhost:8000/rewrite/index.html`
location ^~ /test/ {
rewrite /test/(.+)$ /rewrite/$1 last;
}
rewrite 和 proxy_pass執行順序
- 執行server下的rewrite
- 執行location匹配
- 執行location下的rewrite
rewrite 和 proxy_pass 跳轉域名區別
- rewrite 同一域名跳轉
- proxy_pass 任意域名跳轉
參考資料: