背景:
大平台對各個組件的接口做了統一的NG配置,但是經常發生莫名其妙的問題,各人配置的NG形式不一,也沒人來做
這個規范,網上查閱了不少location,proxy_pass關於左斜杠的說明,結論人雲亦雲,多數是互相copy,本着一勞永逸
的目的把proxy_pass的問題弄清楚,特此做了以下對比測試
實踐過程記錄:
這里先說明:左斜杠 / ,也認為是字符串,使用兩個ng,access.log記錄請求url,結果如下:
client發送的請求為:http://10.192.78.26:8099/a/api
path:待轉發的接口路徑
path1:從path中去掉location字符串后的結果,path = location+path1
proxy_url:轉發后的url中接口路徑部分
result:結果分析
path | location | path1 | proxy_pass(除去ip端口后特點) | proxy_url | result |
/a/api | /a | /api |
|
/a/api | proxy_pass+path |
/a/ | api | /a/api | proxy_pass+path | ||
/a | /api |
|
//api | proxy_pass+path1 | |
/a/ | api | /api | proxy_pass+path1 | ||
/a | /api |
(有字符串b,不以/結尾) |
/b/api | proxy_pass+path1 | |
/a/ | api | /bapi | proxy_pass+path1 | ||
/a | /api |
|
/b//api | proxy_pass+path1 | |
/a/ | api | /b/api | proxy_pass+path1 |
結論:
1、轉發結果和location中是否包含 / 無關,和proxy_pass是否以 / 結尾無絕對關系,這里是想說,/ 對proxy_pass來說,只是一個字符串,和a,b,c沒區別
2、轉發后的url 一定有proxy_pass全部字符串
3、轉發后的url 和 proxy_pass 除去ip,port后是否還有字符串有關,
無字符串,result = proxy_pass+path
有字符串,result = proxy_pass+path1
官網描述分析
規律不算數,結合官網說明驗證規律
官網地址: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass:
注意官網對proxy_pass的定義:uri指去掉domain name( ip address and an optional port)之后的部分,正如上述表格倒數第二列
A request URI is passed to the server as follows:
- If the
proxy_pass
directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive:location /name/ { proxy_pass http://127.0.0.1/remote/; }
翻譯下:如果proxy_pass指令帶有URI,當請求經過服務器時,匹配到location的那部分URI將被指令中的URI代替 (也就是proxy_pass+(path-location))
- If
proxy_pass
is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:location /some/path/ { proxy_pass http://127.0.0.1; }
翻譯下:如果proxy_pass指令不帶URI,當請求經過服務器時,原始客戶端請求將會按相同形式處理, (也就是proxy_pass+path)
因此這里只要將 / 作為正常的字符串看待(URI中的一部分)