Nginx SSL+tomcat集群,request.getScheme() 取到https正确的协议

本文探讨了在Nginx+Tomcat集群架构中,使用HTTPS协议时出现的问题,如请求显示为HTTP而非HTTPS,以及如何通过配置Nginx和Tomcat来解决这些问题。

最近在做一个项目, 架构上使用了 Nginx +tomcat 集群, 且nginx下配置了SSL,tomcat no SSL,项目使用https协议



但是,明明是https url请求,发现 log里面

0428 15:55:55 INFO  (PaymentInterceptor.java:44) preHandle() - requestStringForLog:    {
        "request.getRequestURL():": "http://trade.feilong.com/payment/paymentChannel?id=212&s=a84485e0985afe97fffd7fd7741c93851d83a4f6",
        "request.getMethod:": "GET",
        "_parameterMap":         {
            "id": ["212"],
            "s": ["a84485e0985afe97fffd7fd7741c93851d83a4f6"]
        }
    }

request.getRequestURL() 输出出来的 一直是  

http://trade.feilong.com/payment/paymentChannel?id=212&s=a84485e0985afe97fffd7fd7741c93851d83a4f6

 

但是浏览器中的URL却是

https://trade.feilong.com/payment/paymentChannel?id=212&s=a84485e0985afe97fffd7fd7741c93851d83a4f6

 

 

瞬间要颠覆我的Java观尴尬,API上写得很清楚:

 

getRequestURL():

Reconstructs the URL the client used to make the request. 

The returned URL contains a protocol, server name, port number, and server path, 
but it does not include query string parameters.

也就是说, getRequestURL() 输出的是不带query string的路经(含协议,端口,server path等信息).



并且,还发现

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 的*.conf文件转发选项:

  

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;

proxy_set_header X-Forwarded-Proto $scheme; 加上这句

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

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

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

 

这样以上5项测试就都变为正确的结果了,就像用户在直接访问 Tomcat 一样。

转载于:https://my.oschina.net/u/593517/blog/852644

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值