In this tutorial, we will quickly discuss how to use the try_files directive and learn when and how to use it:
What is The try_files Directive, and How Does It Work?
We usually use the Nginx try_files directive to recursively check if files exist in a specific order and serve the file located first.
The try_file directive is in the server and location blocks and specifies the files and directories in which Nginx should check for files if the request to the specified location is received. A typical try_files directive syntax is as:
try_files $uri $uri/ /default/index.html;
}
The location/block specifies that this is a match for all locations unless explicitly specified location /<name>
Inside the second block, the try_files means if Nginx receives a request to the URI that matches the block in the location, try the $uri first, and if the file is present, serve the file.
For example, if a request such as https://linuxhint.com/blocks/io.sh is received, Nginx will first look for the file inside the /blocks directory and serve the file if available.
The next part (/default/index.html) specifies a fallback option if the file is not in the first param. For example, if the file is not in the /block directory, Nginx will search for the /default directory and serve the file if it exists.
By default, Nginx forbids directory listing, and you will get 403 Forbidden unless you have auto index set to on.
If Nginx fails to find the file in the specified locations, it displays a 404 not found error to the user.
NOTE: Nginx try_files directive recursively searches for files and directories specified from left to right until it finds ones. Specifying this directive in the location / can cause performance issues, especially on sites with massive traffic. Therefore, you should explicitly specify the location block for try_files.
Conclusion
This quick and simple guide has given you an overview of how Nginx try_block works. We recommend diving deep into the Nginx documentation to understand various blocks and when to use them.