详解Nginx proxy_pass的一个/斜杠引发的血案

Laurie ·
更新时间:2024-09-20
· 918 次阅读

背景

一个nginx的server模块下需要proxy到两个server,所以就通过location的不同路径来区分转发到不同的服务器上。

一开始是这么写的

location / { proxy_pass http://server1/; } location /index { proxy_pass http://server2/; }

但是忘记了server1上有个服务路径是/indexNew,结果就被proxy到了server1,出现404问题,然后紧急修改配置如下:

location /indexNew { proxy_pass http://server1/; } location / { proxy_pass http://server1/; } location /index { proxy_pass http://server2/; }

问题现象

结果请求是到了server1了,但是错误变成,POST not supported

{ "status": 500, "message": "http://172.28.72.117/-Request method 'POST' not supported", "result": {} }

这是当时应用的返回错误,查看nginx也没有报错,很奇怪,看了代码里/indexNew的确是POST方法啊,为啥报错不支持呢。

首先这里补充下location各种写法在nginx里的匹配顺序:

分析

nginx日志也没有报错,就尝试抓包,从nginx到应用的包

通过tcpdump命令抓包

tcpdump -w dataAll_normal.pcap -i eth0 -s0 port 8888

类似上述命令抓包,然后通过wireshark看,发现压根没搜索到/indexNew相关的http流量包。

尝试修改location如下

location /indexNew { proxy_pass http://server1; } location / { proxy_pass http://server1/; } location /index { proxy_pass http://server2/; }

区别仅仅在于/indexNew的proxy_pass最后一个/斜杠去掉了,继续抓包,发现可以搜索到/indexNew的包

说明此次修改正确了。

继续改回错误的,尝试抓包,还是没能搜索到/indexNew的包,然后通过IDE远程debug应用

发现到了应用里的URL压根也没有/indexNew,那当然在wireshark包里搜不到了。。。

是因为nginx转发应用的时候,访问路径就只有 / 了。

而工程中请求路径为 / 的接口的确是GET方法

详细看下location中proxy_pass的语法,的确是这样,proxy_pass最后有/,会把匹配location里的路径去掉,截取后面的URL PATH进行转发。

所以这里一定要注意proxy_pass最后一个/的含义作用,要慎用,它会改变路径请求信息,而不是100%的信息转发。

到此这篇关于详解Nginx proxy_pass的一个/斜杠引发的血案的文章就介绍到这了,更多相关Nginx proxy_pass斜杠内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!

您可能感兴趣的文章:nginx proxy_pass指令’/’使用注意事项



斜杠 proxy pass Nginx

需要 登录 后方可回复, 如果你还没有账号请 注册新账号