亲宝软件园·资讯

展开

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

人气:0

前言

今天在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;
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论