服务器之家:专注于服务器技术及软件下载分享
分类导航

云服务器|WEB服务器|FTP服务器|邮件服务器|虚拟主机|服务器安全|DNS服务器|服务器知识|Nginx|IIS|Tomcat|

服务器之家 - 服务器技术 - Nginx - 详解Nginx proxy_pass的一个/斜杠引发的血案

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

2020-12-30 17:49chiweitree Nginx

这篇文章主要介绍了详解Nginx proxy_pass的一个/斜杠引发的血案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

背景

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

一开始是这么写的

?
1
2
3
4
5
6
7
location / {
   proxy_pass http://server1/;
}
 
location /index {
   proxy_pass http://server2/;
}

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

?
1
2
3
4
5
6
7
8
9
10
11
location /indexNew {
   proxy_pass http://server1/;
}
 
location / {
   proxy_pass http://server1/;
}
 
location /index {
   proxy_pass http://server2/;
}

问题现象

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

?
1
2
3
4
5
{
    "status": 500,
    "message": "http://172.28.72.117/-Request method 'POST' not supported",
    "result": {}
}

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

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

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

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

分析

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

通过tcpdump命令抓包

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

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

尝试修改location如下

?
1
2
3
4
5
6
7
8
9
10
11
location /indexNew {
   proxy_pass http://server1;
}
 
location / {
   proxy_pass http://server1/;
}
 
location /index {
   proxy_pass http://server2/;
}

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

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

说明此次修改正确了。

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

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

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

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

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

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

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

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

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

原文链接:https://blog.csdn.net/simonchi/article/details/104547757

延伸 · 阅读

精彩推荐