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

Stella981
• 阅读 726

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

Nginx SSL+Tomcat集群,request.getScheme() 取到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等信息).

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

并且,还发现

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 的转发选项:

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 一样。


关于 RemoteIpValve,有兴趣的同学可以阅读下 doc

http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html

Tomcat port of mod_remoteip, this valve replaces the apparent client remote IP address and hostname for the request with the IP address list presented by a proxy or a load balancer via a request headers (e.g. "X-Forwarded-For").   
   
Another feature of this valve is to replace the apparent scheme (http/https) and server port with the scheme presented by a proxy or a load balancer via a request header (e.g. "X-Forwarded-Proto").

看了下他们的源码,比较简单,在各种框架,各种算法面前,这个类对性能影响很小

  • 如果没有配置protocolHeader 属性, 什么都不做.

  • 如果配置了protocolHeader,但是request.getHeader(protocolHeader)取出来的值是null,什么都不做

  • 如果配置了protocolHeader,但是request.getHeader(protocolHeader)取出来的值(忽略大小写)是 配置的protocolHeaderHttpsValue(默认https),scheme设置为https,端口设置 为 httpsServerPort

  • 其他设置为 http

    if (protocolHeader != null) {
    String protocolHeaderValue = request.getHeader(protocolHeader);
    if (protocolHeaderValue == null) {
    // don't modify the secure,scheme and serverPort attributes
    // of the request
    } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) {
    request.setSecure(true);
    // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0
    request.getCoyoteRequest().scheme().setString("https");

    request.setServerPort(httpsServerPort);
    } else {
    request.setSecure(false);
    // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0
    request.getCoyoteRequest().scheme().setString("http");

    request.setServerPort(httpServerPort);
    }
    }

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Nginx配置https
一、开启nginx的ssl模块1.未安装过nginx,编译安装配置参数如下:./configure\prefix/usr/local/nginx\withpcre\withhttp\_ssl\_modulessl模块\withhttp\_stub\_status\_module\wit
Wesley13 Wesley13
2年前
4. Nginx模块
Nginx官方模块1.ngx\_http\_stub\_status\_modulehttp://nginx.org/en/docs/http/ngx\_http\_stub\_status\_module.html。(https://www.oschina.net/action/GoToLink?urlhttp%3A%2
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这