How to Use NGINX try_files

NGINX is a feature-rich web server that can also be used as load balancer and reverse proxy. try_files is one of its key features that allows you to configure how to serve files based on various requests received. In this article, we will look at what is try_files, how does it work and how to use NGINX try_files.


What is NGINX try_files

try_files is a server directive in NGINX that allows your server to sequentially check if a list of files exist and serve the first matching one. It enables NGINX to try responding with different files one after the other, in case it is unable to find a matching file to send.

Also read : Difference between ServerName and ServerAlias


How to Use NGINX try_files

Here is an example that uses try_files.

location / {
    try_files $uri $uri/ /default/index.html;
}

In the above example, when a user requests a URL, NGINX will try $uri that is the requested URL as-is. If that returns 404 page not found response, then NGINX will try $uri/, that is the requested URL with a forward slash. It will do this without sending the 404 response code to the user. If both these return 404 response code, then NGINX will simply return the html file at /default/index.html, as a fallback option.

Only if all these options fail, then NGINX will return 404 response code.

It is important to note that NGINX will try serving requested URLs based on the specified files & directories listed after try_files directive, from left to right.

Also, try_files is typically placed in server or location blocks in NGINX.

Also read : How to Install NFS Server & Client in CentOS

That’s it. As you can see, try_files enables NGINX to check the existence of a specified list of files and use the first one found for processing.