Nginx在反向代理使用中proxy_pass的末尾带斜杠 /和不带的区别

一、 实验环境

URL的一般语法格式为:protocol :// hostname[:port] / path / [:parameters][?query]#fragment
   当proxy_pass 指令后的URL带路径【即是/或/path】和不带路径时,Nginx反向代理传递给后端服务器的请求存在不同。
   客户端的请求:http://192.168.241.137:10180/urltest/test
   Nginx代理服务器IP: 192.168.241.137 端口为10180
   后端Nginx服务器IP:192.168.241.141 端口为18081
   Nginx web服务器的配置

image.png

二、实验过程

实验一:代理请求为 http://192.168.241.141:18081和http://192.168.241.141:18081/时

1、代理请求为 http://192.168.241.141:18081
(1) location 有 / 时

image.png

image.png

代理服务器传给后端的请求为 http://192.168.241.141:18081/urltest/test
(2) location 没有 / 时
image.png

代理服务器传给后端的请求为 http://192.168.241.141:18081/urltest/test

2 当代理请求为 http://192.168.241.141:18081/时
(1) location有 /

image.png

代理服务器传给后端的请求为:http://192.168.241.141:18081/test
(2) location 没有 /
image.png

代理服务器传给后端的请求为:http://192.168.241.141:18081//test

总结:

当proxy_pass请求的url后面没有 / 时, location匹配部分也属于请求部分,都会将整个请求都将加到proxy_pass请求的url部分,即后端接收到的请求为http://192.168.241.141:18081/urltest/test

当proxy_pass请求的url后面存在/ 时,localtion匹配部分只是用于匹配,不属于请求部分,需要在客户端请求部分将location匹配部分减去:
location 匹配 /urltest , 则是 http://192.168.241.141:18081/+(/urltest/test - /urltest), 即http://192.168.241.141:18081//test

location 匹配 /urltest/, 则是 http://192.168.241.141:18081/+(/urltest/test - /urltest/), 即http://192.168.241.141:18081/test

实验二:当代理请求为 http://192.168.241.141:18081/webhttp://192.168.241.141:18081/web/

1、当请求为 http://192.168.241.141:18081/web
(1) location 有 /

image.png

后端服务器接收到的请求为: http://192.168.241.141:18081/web +(/urltest/test - /urltest/), 即为: http://192.168.241.141:18081/webtest
(2) 当location 没有 / 时
image.png

后端服务器接收到的请求为:http://192.168.241.141:18081/web +(/urltest/test - /urltest), 即为 :http://192.168.241.141:18081/web/test

2、当代理请求为 http://192.168.241.141:18081/web/
(1) location 有 / 时

image.png

后端服务器接收到的请求为:http://192.168.241.141:18081/web/ +(/urltest/test - /urltest/), 即为 :http://192.168.241.141:18081/web/test
(2) location没有 / 时
image.png

后端服务器接收到的请求为:http://192.168.241.141:18081/web/ +(/urltest/test - /urltest ), 即为 :http://192.168.241.141:18081/web//test

三、 结论

proxy_pass配置中url末尾不存在路径信息时,则直接客户端的请求拼接在proxy_pass中url之后; proxy_pass配置中url末尾存在路径信息时 则将原客户端请求去除location匹配表达式后的内容拼接在proxy_pass中的url之后。

转载自:https://mp.weixin.qq.com/s?__biz=MzkxOTQyNjE5Nw==&mid=2247484035&idx=1&sn=b3621872e6bbdd1446bbc264961915a6&chksm=c1a30779f6d48e6f87d2f8674551dea05057d95046d44cc15d94c3ff3fca59d1af000a95065b&scene=132#wechat_redirect
仅供自己查看,感谢作者的整理。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容