您当前的位置:首页 > 网站建设 > 网站维护
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery |

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

51自学网 2022-07-04 11:37:49
  网站维护

背景

一个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_cache 缓存配置详解
Nginx实现https网站配置代码实例
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1