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

网上浏览了不少location,proxy_pass关于左斜杠的说明,结论人云亦云,互相copy,为了彻底搞清楚这个问题,决定通过对比测试来找规律

这里先说明:左斜杠 / ,也认为是字符串,使用两个ng,access.log记录请求url,结果如下表

其中path1 = path - location,proxy_url代表转发后的请求,result为分析的结果,client发送的请求为:http://10.192.78.26:8099/a/api

path location proxy_pass path1 proxy_url proxy_pass后字符串特点 result
/a/api /a
http://10.192.77.229:8091
/api /a/api
无字符串
proxy_pass+path
/a/ api /a/api proxy_pass+path
/a
http://10.192.77.229:8091/
/api //api
有字符串/
proxy_pass+path1
/a/ api /api proxy_pass+path1
/a
http://10.192.77.229:8091/b
/api /b/api
有字符串b,不以/结尾
proxy_pass+path1
/a/ api /bapi proxy_pass+path1
/a
http://10.192.77.229:8091/b/
/api /b//api
有字符串b,以/结尾
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中的一部分)

原文地址:https://www.cnblogs.com/yb38156/p/12173626.html