简体   繁体   中英

How to force Spring Boot to redirect to https instead of http?

I use Spring Boot + Spring Security. We use nginx on production which proxy_pass requests to our application. The problem is that app redirects to http instead of https (when user logs out).

How to force Spring to redirect to https on production env and still redirect to http on dev env?

I think the best solution is to turn on

server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto

in your embedded tomcat and let spring write the correct redirect headers.

Be sure to include the configuration in your nginx.conf like:

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;

But be sure that your nginx is in the address range of server.tomcat.internal_proxies otherwise you have to change the range (which is for example necessary, when using docker-machine and container linking).

The problem is that nginx is most talking to your app via HTTP, and the app believes (correctly) that the request came for a HTTP URL, so when calculating URLs for redirection, it will also end up with HTTP. There are multiple ways to solve this...

A quick Google search seems to indicate there's an AJP module for nginx. Maybe you can use that instead of HTTP proxy? That would probably solve it as there would be no HTTP traffic between nginx and the app (thus no HTTPS->HTTP switch).

Another way would be to set X-Forwarded-Proto header in nginx and make Spring Boot aware of it .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM