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" />
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?