Nginx

How to use Nginx try_files

Nginx is a powerful web server that gives us lots of features and customization for various needs. One of the Nginx server’s capacities is its ability to use directives to configure the server in a simple, clean, and reliable way. A commonly-used directive is the try_files that allow us to configure URI location and how Nginx serves various files based on the request received.

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:

location / {
    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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list