Resolve that nginx did not jump to upstream address

  • 2020-05-17 07:46:09
  • OfStack

preface

Today, I encountered a very strange problem in nginx. When the front page of tomcat was redirected to the address of upstream, I directly reported 404. However, some page visits were normal.

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

If it is normal to access ip directly from the Intranet, it can be determined that it is a problem of nginx. nginx is configured as follows


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; 
  } 
 }

After checking, it is found that in the back-end java code, this address is redirected jump, and request.getServerPort () is used in it. If the jump through nginx is unable to get the correct port at the front end, the default return is still 80. If the listening port of nginx is not 80 by default, response.sendRedirect will not be able to jump to the correct address.


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;
  }

The solution is to add the port number to the nginx configuration file proxy_set_header


proxy_set_header Host $host:$proxy_port;

Related articles: