Nginx proxy_pass 路徑末尾加不加 / 的問題


今天在配置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

  1. 帶/實際訪問的是 http://localhost:8000/index.html (相當於根或絕對路徑,不會在代理路徑后拼接locaiton中匹配規則的路徑,比如上邊的test)
  2. 無/實際訪問的是 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 任意域名跳轉

參考資料:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM