Removing Port Numbers in Nginx Try Files Redirect
Removing port numbers in Nginx try_files redirect
Suyash Singh
Posted by Suyash Singh
on October 15, 2022
Photo by Ave on Unsplash

When a user tries to access a URL which maps to a static resource on the web server, Nginx’s try_files is the de facto way of specifying the order in which such requests should be processed.

If the request is for the index HTML page accessible via the URL https://example.com/projects, Nginx can be configured to be smart enough to know whether this URL corresponds to a file or a directory and serve the request accordingly.

For example, the following configuration for each request would first try to serve the file present at the requested location, if this fails, it would try to serve the index.html present inside the directory specified by the requested location. And, as a catch-all scenario will serve the 404 error page if it is unable to serve the index.html file for the directory.

server {

    listen         81 default_server;
    listen         [::]:81 default_server;
    server_name    example.com;
    root           /var/www/html/example.com/public;
    index          index.html;
    try_files $uri $uri/ =404;

}

The default behavior of try_files is that it issues a redirect to the client if the requested location cannot be served by the first argument but can be served by the next arguments of try_files. When this happens, by default the redirect issued has the port number embedded into it. To understand it, let’s take an example:

If the initial request was for http://example.com/projects, where projects is a directory

First argument of try_files would not be able to serve the resource since it’s a directory

Nginx moves to the next argument of the try_files, if it is successfully found, it issues a redirect to the client for the new location: http://example.com:81/projects/

However, Depending on where Nginx sits in our architecture, there may be a case where the clients won’t be able to access our Nginx’s server port 81 directly.

To handle such scenario we would want Nginx to not include the port numbers in the redirect issued.

To do so, we simply need to specify port_in_redirect as off like this:

server {
    listen         81 default_server;
    listen         [::]:81 default_server;
    server_name    example.com;
    root           /var/www/html/example.com/public;
    index          index.html;
    
    port_in_redirect off;
    
    try_files $uri $uri/ =404;

}