Nginx开启https负载均衡,配置Tomcat识别http和https协议

2018-03-20 23:41:42
977次阅读
0个评论

常见的是 Nginx+Tomcat 这种两层配置,Nginx 作为负载均衡服务,Nginx上开启https,  后端使用Tomcat,  两者之间走http协议。

如果不做其它特殊配置,则Tomcat 认为所有的请求都是 Nginx 发出来的,这样会导致如下的错误结果:

request.getScheme()  //总是 http,而不是实际的http或https
request.isSecure()  //总是false(因为总是http)
request.getRemoteAddr()  //总是 nginx 请求的 IP,而不是用户的IP
request.getRequestURL()  //总是 nginx 请求的URL 而不是用户实际请求的 URL
response.sendRedirect( 相对url )  //总是重定向到 http 上 (因为认为当前是 http 请求)

解决以上问题很简单,只需要分别配置一下 Nginx 和 Tomcat 就好了,而不用改程序。



使用Nginx 的转发请求下,Tomcat 识别用户的直接请求(https还是http )

配置 Nginx 的转发选项:


proxy_set_header       Host $host;
proxy_set_header  X-Real-IP  $remote_addr;
proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto  $scheme;




配置Tomcat server.xml 的 Engine 模块下配置一个 Value:

<Valve className="org.apache.catalina.valves.RemoteIpValve" remoteIpHeader="X-Forwarded-For"protocolHeader="X-Forwarded-Proto" protocolHeaderHttpsValue="https"/>

配置双方的 X-Forwarded-Proto 就是为了正确地识别实际用户发出的协议是 http 还是 https。X-Forwarded-For 是为了获得实际用户的 IP。



收藏00

登录 后评论。没有帐号? 注册 一个。