Nginx equivalent of UseCanonicalName (external name/port)

bmoody asked:

I have nginx running behind a front-end proxy, so while nginx is listening on port 8080, clients must actually connect to port 80.

This means that if a client requests a URL corresponding to a directory, but the final slash is missing, they receive a 301 redirection to the wrong location.

Simplified configuration:

server {
    listen 8080 default_server;
    server_name example.com;
    root /srv/www/html;
    autoindex on;
}

Assume that /srv/www/html/foo is a directory. If I then run curl -I http://localhost:8080/foo, I receive:

HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.3
Date: Tue, 18 Jun 2019 20:22:13 GMT
Content-Type: text/html
Content-Length: 185
Location: http://localhost:8080/foo/
Connection: keep-alive

when what I want to see is:

...
Location: http://localhost/foo/
...

(i.e., the location to which clients are redirected has a different port number than the one on which nginx actually receives the connection.)

(I don’t particularly care whether nginx uses the hostname from the Host header or the hostname specified by server_name in this case.)

With Apache, this can be done by setting UseCanonicalName. How can this be done with Nginx?

My answer:


You use the port_in_redirect directive.

port_in_redirect off;

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.