在進(jìn)行nginx反向代理配置的時(shí)候,location和proxy_pass中的斜線會(huì)造成各種困擾,有時(shí)候多一個(gè)或少一個(gè)斜線,就會(huì)造成完全不同的結(jié)果,所以特地將location和proxy_pass后有無斜線的情況進(jìn)行了排列組合,進(jìn)行了一次完整的測(cè)試,找出原理,以提高姿勢(shì)水平~
〇. 環(huán)境信息
兩臺(tái)nginx服務(wù)器
nginx A: 192.168.1.48
nginx B: 192.168.1.56
一. 測(cè)試方法
在nginx A中配置不同的規(guī)則,然后請(qǐng)求nginx A: http://192.168.1.48/foo/api
觀察nginx B收到的請(qǐng)求,具體操作是查看日志中的$request字段
二. 測(cè)試過程及結(jié)果
案例1
nginx A配置:
location /foo/ { proxy_pass http://192.168.1.56/;}
nginx B收到的請(qǐng)求:/api
案例2
nginx A配置:
location /foo/ { proxy_pass http://192.168.1.56/;}
nginx B收到的請(qǐng)求://api
案例3
nginx A配置:
location /foo/ { proxy_pass http://192.168.1.56/;}
nginx B收到的請(qǐng)求:/foo/api
案例4
nginx A配置:
location /foo/ { proxy_pass http://192.168.1.56/;}
nginx B收到的請(qǐng)求:/foo/api
案例5
nginx A配置:
location /foo/ { proxy_pass http://192.168.1.56/bar/;}
nginx B收到的請(qǐng)求:/bar/api
案例6
nginx A配置:
location /foo { proxy_pass http://192.168.1.56/bar/;}
nginx B收到的請(qǐng)求:/bar//api
案例7
nginx A配置:
location /foo/ { proxy_pass http://192.168.1.56/bar;}
nginx B收到的請(qǐng)求:/barapi
案例8
nginx A配置:
location /foo { proxy_pass http://192.168.1.56/bar;}
nginx B收到的請(qǐng)求:/bar/api
看到這里是不是都暈了呢,其實(shí)是有規(guī)律的
現(xiàn)在把這些案例按表格排列起來,結(jié)果表示nginx B收到的請(qǐng)求
表一
案例 | location | proxy_pass | 結(jié)果 |
---|---|---|---|
1 | /foo/ | http://192.168.1.48/ | /api |
2 | /foo | http://192.168.1.48/ | //api |
3 | /foo/ | http://192.168.1.48 | /foo/api |
4 | /foo | http://192.168.1.48 | /foo/api |
表二
案例 | location | proxy_pass | 結(jié)果 |
---|---|---|---|
5 | /foo/ | http://192.168.1.48/bar/ | /bar/api |
6 | /foo | http://192.168.1.48/bar/ | /bar//api |
7 | /foo/ | http://192.168.1.48/bar | /barapi |
8 | /foo | http://192.168.1.48/bar | /bar/api |
三. 解析
原請(qǐng)求路徑:本文中統(tǒng)一為 "/foo/api"
location: 上面表格中的location列
proxy_pass:上面表格中的proxy_pass列
新請(qǐng)求路徑:nginx將原請(qǐng)求路徑處理過后的字符串
重點(diǎn)對(duì) proxy_pass 進(jìn)行分析,可以分為3種形式
然后按照ip:port后是否接了字符串歸為2類,"/"也是字符串,因此1歸為一類,2、3歸為一類,下面對(duì)這兩類情況進(jìn)行說明
當(dāng) proxy_pass 的 ip:port 后未接字符串的時(shí)候,nginx 會(huì)將原請(qǐng)求路徑原封不動(dòng)地轉(zhuǎn)交給下一站 nginx,如案例3和4
當(dāng) proxy_pass 的 ip:port 后接了字符串的時(shí)候,nginx 會(huì)將 location 從 原請(qǐng)求路徑 中剔除,再將剩余的字符串拼接到 proxy_pass 后生成 新請(qǐng)求路徑,然后將 新請(qǐng)求路徑 轉(zhuǎn)交給下一站nginx(上面一種情況實(shí)際上和這個(gè)是一樣的,只不過剔除的字符串是空串~~)
舉個(gè)最讓人疑惑的例子:案例7。proxy_pass 的 ip:port 后接了字符串 "/bar",因此將 location:"/foo/" 從 原請(qǐng)求路徑:"/foo/api" 中剔除,變?yōu)?quot;api",再將"api"拼接到proxy_pass: http://192.168.1.48/bar 后生成了新請(qǐng)求url:" http://192.168.1.48/barapi ",因此下一站的nginx收到的請(qǐng)求就是 "/barapi"。
案例6:proxy_pass 的 ip:port 后接了字符串 "/bar/",因此將 location:"/foo" 從 原請(qǐng)求路徑 "/foo/api" 中剔除,變?yōu)?"/api",再將 "/api" 拼接到proxy_pass: http://192.168.1.48/bar/ 后生成了 新請(qǐng)求路徑:" http://192.168.1.48/bar//api ",因此下一站的nginx收到的請(qǐng)求就是 /bar//api。
其它的案例都可以以此類推,現(xiàn)在終于搞明白了,再也不用一頭霧水。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
|
新聞熱點(diǎn)
疑難解答
圖片精選