關於nginx沒有跳轉到upstream地址

  • 前言

今天在nginx碰到一個很奇怪的問題,在前端tomcat跳轉頁面的時候跳轉的是upstream的地址,直接就報404,可是有些頁面訪問又是正常的。html

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 就沒法跳轉到正確的地址。java

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上加上端口號nginx

proxy_set_header Host       $host:$proxy_port;
相關文章
相關標籤/搜索