随笔 - 19  文章 - 0  评论 - 4  阅读 - 46772

nginx反代后java的request.getScheme获取不到https的解决办法

在实际应用中,经常会用到nginx反向代理应用,这中就会出现一中情况,访问https页面Java 通过request.getScheme()获取不到https协议,或者response.sendRedirect重定向是http,而不是我们想要的https。

问题原因

经过反代后,协议信息没有转发到后端,或者后端没有设置protocolHeader

nginx配置

需要在nginx的配置文件的server段加上proxy_set_header X-Forwarded-Proto $scheme,
nginx的server完整配置如下(仅做参考):

复制代码
server {
        listen 80;
        server_name www.example.com;
        index    index.html index.htm index.jsp;
        error_log   /var/log/weblogs/error/www.example.com_error.log crit;
        access_log  /var/log/weblogs/access/www.example.com_access.log  access;
        rewrite ^(.*)\;(.*)$ $1 last;
        location / {
            proxy_pass http://127.0.0.1:1088/;
            proxy_redirect off;
            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;
        }

}
复制代码

Spring Boot解决办法

Spring Boot 应用只需要在application.yml配置文件加上以下配置即可:

server:
  tomcat:
    remoteip:
      protocol-header: "X-Forwarded-Proto"
      remote-ip-header: "X-FORWARDED-FOR"

Tomcat 解决办法

tomcat 有两种方式
方式一:在conf/server.xml的Engine节点中加入一个value,

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

如下图:

    

方式二:在conf/server.xml的Connector节点中加一个参数scheme=“https”

<Connector port="1088" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" scheme="https" />

 

posted on   尹镇镇  阅读(980)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示