Nginx – Reverse-proxied nginx exposing port number when redirecting directory index requests

nginx

I have nginx backend that's used to serve static files. Nginx is running on a non-standard port (e.g. 8080). It is publicly accessible via a reverse proxy on port 80.

The setup works fine for the most part. However, if a request is made to a directory, nginx returns a 301 redirect with the port set to 8080.

All the questions I could find were about nginx being a reverse proxy rather than the actual server. Any help would be very much appreciated!

As an illestration of this problem, the URL http://example.com/dir/ works fine. But leaving the trailing slash http://example.com/dir causes the browser to redirect to http://example.com:8080/dir.

Best Answer

There is port_in_redirect directive for this. You should turn it off.

server {
    ...
    port_in_redirect off;
    ...
}

Also, it's better to test redirects (especially permanent redirects) with console tools like curl or wget, because your browser is likely already cached redirect and will just use it without actual hit to the server (that's the main reason of permanent redirect).