1. 程式人生 > >小牛帶你nginx反向代理中神奇的斜線

小牛帶你nginx反向代理中神奇的斜線

方法 測試 ref 結果 原理 一次 觀察 服務器 bar

在進行nginx反向代理配置的時候,location和proxy_pass中的斜線會造成各種困擾,有時候多一個或少一個斜線,就會造成完全不同的結果,所以特地將location和proxy_pass後有無斜線的情況進行了排列組合,進行了一次完整的測試,找出原理,以提高姿勢水平~

〇. 環境信息
兩臺nginx服務器

nginx A: 192.168.1.48

nginx B: 192.168.1.56

一. 測試方法
在nginx A中配置不同的規則,然後請求nginx A:http://192.168.1.48/foo/api
觀察nginx B收到的請求,具體操作是查看日誌中的$request字段
二. 測試過程及結果

案例1nginx A配置:

location /foo/ { proxy_pass http://192.168.1.56/; } nginx B收到的請求:/api

案例2nginx A配置:

location /foo/ { proxy_pass http://192.168.1.56/; } nginx B收到的請求://api

案例3nginx A配置:

location /foo/ { proxy_pass http://192.168.1.56/; } nginx B收到的請求:/foo/api

案例4nginx A配置:

location /foo/ {
proxy_pass http://192.168.1.56/;
}
nginx B收到的請求:/foo/api

案例5nginx A配置:

location /foo/ { proxy_pass http://192.168.1.56/bar/; } nginx B收到的請求:/bar/api

案例6nginx A配置:

location /foo { proxy_pass http://192.168.1.56/bar/; } nginx B收到的請求:/bar//api

案例7nginx A配置:

location /foo/ { proxy_pass http://192.168.1.56/bar; } nginx B收到的請求:/barapi

案例8nginx A配置:

location /foo { proxy_pass http://192.168.1.56/bar; } nginx B收到的請求:/bar/api

然後按照ip:port後是否接了字符串歸為2類,"/"也是字符串,因此1歸為一類,2、3歸為一類,下面對這兩類情況進行說明

當 proxy_pass 的 ip:port 後未接字符串的時候,nginx 會將原請求路徑原封不動地轉交給下一站 nginx,如案例3和4

當 proxy_pass 的 ip:port 後接了字符串的時候,nginx 會將 location 從 原請求路徑 中剔除,再將剩余的字符串拼接到 proxy_pass 後生成 新請求路徑,然後將 新請求路徑 轉交給下一站nginx(上面一種情況實際上和這個是一樣的,只不過剔除的字符串是空串~~)

舉個最讓人疑惑的例子:案例7。proxy_pass 的 ip:port 後接了字符串 "/bar",因此將 location:"/foo/" 從 原請求路徑:"/foo/api" 中剔除,變為"api",再將"api"拼接到proxy_pass:http://192.168.1.48/bar 後生成了新請求url:"http://192.168.1.48/barapi",因此下一站的nginx收到的請求就是 "/barapi"。

案例6:proxy_pass 的 ip:port 後接了字符串 "/bar/",因此將 location:"/foo" 從 原請求路徑 "/foo/api" 中剔除,變為 "/api",再將 "/api" 拼接到proxy_pass:http://192.168.1.48/bar/ 後生成了 新請求路徑:"http://192.168.1.48/bar//api",因此下一站的nginx收到的請求就是 /bar//api。

小牛帶你nginx反向代理中神奇的斜線

小牛帶你nginx反向代理中神奇的斜線