关于nginx没有跳转到upstream地址的解决

2025-05-26 0 73

前言

今天在nginx碰到一个很奇怪的问题,在前端tomcat跳转页面的时候跳转的是upstream的地址,直接就报404,但是有些页面访问又是正常的。

http://tomcat/tomcat-web/account/index

如果直接用内网ip访问是正常的,所以可以判定是nginx的问题,nginx配置如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
upstream tomcat {

server 192.168.11.172:8061;

server 192.168.11.172:8062;

ip_hash;

}

server {

listen 8060;

server_name www.example.com;

location / {

proxy_pass http://tomcat;

proxy_set_header Host $host:8060;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

index index.html index.htm;

}

}

经过排查发现,因为在后端java代码中,这个地址是用重定向跳转,里面用到request.getServerPort()如果是通过nginx跳转是获取不到前端正确的端口,默认返回的仍然是80,如果nginx的监听的端口默认不是80的话,response.sendRedirect 就无法跳转到正确的地址。

?

1
response.sendRedirect(getBasePath(request) + "account/index");
?

1

2

3

4

5

6
private String getBasePath(HttpServletRequest request) {

String path = request.getContextPath();

String basePath = request.getScheme() + "://" + request.getServerName()

+ ":" + request.getServerPort() + path + "/";

return basePath;

}

解决方法是在nginx的配置文件proxy_set_header上加上端口号

?

1
proxy_set_header Host $host:$proxy_port;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://segmentfault.com/a/1190000020371007

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 关于nginx没有跳转到upstream地址的解决 https://www.kuaiidc.com/52853.html

相关文章

发表评论
暂无评论