欢迎光临
我们一直在努力

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

前言

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

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

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

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 就无法跳转到正确的地址。

response.sendRedirect(getBasePath(request) + "account/index");
  private String getBasePath(HttpServletRequest request) {
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName()
        + ":" + request.getServerPort() + path + "/";
    return basePath;
  }

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

proxy_set_header Host $host:$proxy_port;

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

本文从互联网转载,来源地址:www.downzz.com/fuwuqi/188066.html,原作者保留一切权利,若侵权或引用不当,请联系九八云(cmy.cn)删除。【九八云,优质云服务器提供商】

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。