fedor.belov
fedor.belov

Reputation: 23343

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?

Upvotes: 3

Views: 4421

Answers (2)

Christian Metzler
Christian Metzler

Reputation: 3249

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).

Upvotes: 6

kaqqao
kaqqao

Reputation: 15479

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.

Upvotes: 1

Related Questions