【问题标题】:How to force Spring Boot to redirect to https instead of http?如何强制 Spring Boot 重定向到 https 而不是 http?
【发布时间】:2015-05-17 23:59:54
【问题描述】:
我使用 Spring Boot + Spring Security。我们在proxy_pass 向我们的应用程序请求的生产中使用nginx。问题是应用程序重定向到http 而不是https(当用户注销时)。
如何强制 Spring 在生产环境中重定向到 https 并仍然在开发环境中重定向到 http?
【问题讨论】:
标签:
spring
configuration
spring-security
spring-boot
【解决方案1】:
我认为最好的解决办法是开启
server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
在您的嵌入式 tomcat 中,让 spring 编写正确的重定向标头。
确保在你的 nginx.conf 中包含如下配置:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Forwarded-Proto $scheme;
但请确保您的 nginx 在server.tomcat.internal_proxies 的地址范围内,否则您必须更改范围(例如,在使用 docker-machine 和容器链接时这是必要的)。
【解决方案2】:
问题是 nginx 与您的应用程序通过 HTTP 通信最多,并且应用程序(正确地)认为请求来自 HTTP URL,因此在计算用于重定向的 URL 时,它也会以 HTTP 结束。有多种方法可以解决这个问题...
快速的 Google 搜索似乎表明 nginx 有一个 AJP 模块。也许您可以使用它而不是 HTTP 代理?这可能会解决它,因为 nginx 和应用程序之间没有 HTTP 流量(因此没有 HTTPS->HTTP 开关)。
另一种方法是在 nginx 和 make Spring Boot aware of it 中设置 X-Forwarded-Proto 标头。