Nginx – How to Prevent Port Change on Redirect

nginxportredirectionvarnish

I currently have nginx setup to serve content through Varnish. Nginx listens on port 8000 and varnish connects users' requests from 80 to 8000.

The problem is, on some occasions, particularly when trying to hit a directory, like site.com/2010, nginx is redirecting the request to site.com:8000/2010/.

How can I prevent this?

Best Answer

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.