关于nginx没有跳转到upstream地址的解决
前言
今天在nginx碰到一个很奇怪的问题,在前端tomcat跳转页面的时候跳转的是upstream的地址,直接就报404,但是有些页面访问又是正常的。
http://tomcat/tomcat-web/account/index
如果直接用内网ip访问是正常的,所以可以判定是nginx的问题,nginx配置如下
upstreamtomcat{
server192.168.11.172:8061;
server192.168.11.172:8062;
ip_hash;
}
server{
listen8060;
server_namewww.example.com;
location/{
proxy_passhttp://tomcat;
proxy_set_headerHost$host:8060;
proxy_set_headerX-Real-IP$remote_addr;
proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;
indexindex.htmlindex.htm;
}
}
经过排查发现,因为在后端java代码中,这个地址是用重定向跳转,里面用到request.getServerPort()如果是通过nginx跳转是获取不到前端正确的端口,默认返回的仍然是80,如果nginx的监听的端口默认不是80的话,response.sendRedirect就无法跳转到正确的地址。
response.sendRedirect(getBasePath(request)+"account/index");
privateStringgetBasePath(HttpServletRequestrequest){
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()
+":"+request.getServerPort()+path+"/";
returnbasePath;
}
解决方法是在nginx的配置文件proxy_set_header上加上端口号
proxy_set_headerHost$host:$proxy_port;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。