Prevent port change on redirect in nginx

Solution 1:

I found the answer to this question by more carefully reading the HttpCoreModule docs.

port_in_redirect off;

This retains the port used by the client during redirects. Closely related is server_name_in_redirect which uses the first hostname for redirects. As I didn't want sitename.v.myserver.com to redirect to sitename.com,

Solution 2:

I my case nginx listens to port 80 inside a docker container but it's mapped to port 8080 (or any random port) outside the container. There is no reverse proxy in-between that can add proper headers for port and also don't want to hardcode it in the nginx configuration.

Example of wrong redirect:

http://localhost:8080/directory -> http://localhost/directory/

I tried:

server {
  # ...
  port_in_redirect off;
  server_name_in_redirect off;
  # ...
}

But didn't work. The only thing that worked well was:

server {
  # ...
  absolute_redirect off;
  # ...
}

Manual entry forabsolute_redirect says:

If disabled, redirects issued by nginx will be relative.

I find this to be more flexible and doesn't require you to have the server name and port hardcoded anywhere.

If you are worried about redirects with relative URLs check this comment.


Solution 3:

The code behind NGINX probably uses the FASTCGI variable SERVER_PORT to determine where to direct the user. SERVER_PORT will contain the port nginx listens on, so that would be 8000 in your case.

You can try something like this for testing purpose:

location ~ \.php$ {
        [...]
        fastcgi_param  SERVER_PORT 80;
}

adapted to your configuration. That's a dirty hack but can help you diagnose the problem.


Solution 4:

For those who have

  • Varnish listens port 80
  • backend server (in my case nginx) listens port 8080

The fastcgi_param SERVER_PORT should be same as the frontend.

So, I set

fastcgi_param  SERVER_PORT 80;

to redirect to appropriate URL from nginx.