Using ServletUriComponentsBuilder with Nginx

Posted at — Mar 13, 2017

Spring’s ServletUriComponentsBuilder.fromCurrentRequest() can be really convinient to build an URL from the current request. However, when using Nginx, things might work so well.

The solution is simple, just add these headers to your Nginx configuration file:

proxy_set_header        X-Forwarded-Host   $host:443;
proxy_set_header        X-Forwarded-Server $host;
proxy_set_header        X-Forwarded-Port   443;
proxy_set_header        X-Forwarded-Proto  https;

UPDATE 2020-06-08

You need to enable support for this in Spring Boot by setting the following property (Since Spring Boot 2.2):

server.forward-headers-strategy=native
If you want to be notified in the future about new articles, as well as other interesting things I'm working on, join my mailing list!
I send emails quite infrequently, and will never share your email address with anyone else.