Nginx学习——location+proxy_pass左斜杠问题彻底弄清

背景:

大平台对各个组件的接口做了统一的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


http://10.192.77.229:8091(无字符串)

/a/api proxy_pass+path
/a/ api /a/api proxy_pass+path
/a /api


http://10.192.77.229:8091/有字符串/

//api proxy_pass+path1
/a/ api /api proxy_pass+path1
/a /api


http://10.192.77.229:8091/b

(有字符串b,不以/结尾)

/b/api proxy_pass+path1
/a/ api /bapi proxy_pass+path1
/a /api


http://10.192.77.229:8091/b/(有字符串b,以/结尾)

/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中的一部分)

posted @ 2020-01-09 21:28  鼠标的博客  阅读(2827)  评论(3编辑  收藏  举报