1、location后面带 / ,proxy_pass 后面不带 /

location /aaa/{
    proxy_pass http://127.0.0.1:9099/test4/hello/getProxyUrl;
}

 

测试地址:http://localhost:10000/aaa/123

 测试结果:请求失败!

实际地址 http://127.0.0.1:9099/test4/hello/getProxyUrl123,参数123直接拼接放在了最后,且没有 / ,导致请求失败

 

 2、location后面带 / ,proxy_pass 后面带 /

 

 测试结果:成功!实际地址为:http://127.0.0.1:9099/test4/hello/getProxyUrl/123,参数123拼接在了最后

 

3、location后面不带 / ,proxy_pass 后面带 /

location /aaa{
    proxy_pass http://127.0.0.1:9099/test4/hello/getProxyUrl/;
}

 

 

 

测试结果:成功!实际地址为:http://127.0.0.1:9099/test4/hello/getProxyUrl//123,参数123拼接在了最后,且多了个 /

 

4、location后面不带 / ,proxy_pass 后面不带 /

location /aaa{
    proxy_pass http://127.0.0.1:9099/test4/hello/getProxyUrl;
}

 

 测试结果:成功!实际地址为:http://127.0.0.1:9099/test4/hello/getProxyUrl/123,参数123拼接在了最后

 

5、location匹配中如何把参数拼接到proxy_pass后面的呢?以location不带 / 为例,因为结果看的更清楚

location /aaa{
    proxy_pass http://127.0.0.1:9099/test4/hello/getProxyUrl/;
}

测试地址为localhost:10000/aaaBBBB ,可以看到地址中并没有传递参数,但看下面的运行结果,请求成功了,且参数为BBBB

 

 nginx从/aaa处截断,一分为二,/aaa后面的字符串会原封不动的拼接到proxy_pass后面。location后面的 / 只会影响url匹配,proxy_pass后面的 / 只会影响实际url的拼接。

 

总结:location、proxy_pass最好都带 / ,或者都不带 /;url匹配时,location后面的 / 就是一个普通字符来处理,没有特殊的含义。而proxy_pass中的 / 是资源分割符,是个特殊字符。

  区别:location带 / 时,像 /aaaBBB 这种是不会匹配的;location不带 / ,像 /aaaBBB 这种是会匹配的。location带与不带 / 看实际需求。

 Tip:  多个location规则优先匹配最长字符串的

posted on 2023-02-21 11:19  李白菜  阅读(688)  评论(0编辑  收藏  举报