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 2023-09-19 11:11  尹镇镇  阅读(1342)  评论(0)    收藏  举报