try_files
The `try_files` directive attempts to serve files from specified paths, falling back to a specified URI if no files are found.
Description
The try_files directive is used in NGINX to specify a list of file paths that NGINX will check for existence in order to serve a request. It can take multiple arguments, which represent file paths or URIs that NGINX will attempt to serve in order. If NGINX finds a file that exists at one of the specified paths, it will serve that file. If none of the specified files exist, NGINX can fall back to serving a predefined URI, which can be useful for routing requests to a different handler.
The syntax requires at least two arguments: a list of paths to check and at least one fallback URI. The directive will check each path sequentially until it finds an existing file. If none of the specified files are found, the last argument, which must be an URI, is used. This allows for graceful handling of missing files by falling back to error pages or redirecting to non-existing routes, such as for a SPA framework.
The try_files directive works particularly well with locations where URL rewriting is common, such as in single-page applications or dynamically managed files. By leveraging the order of files passed to try_files, developers can create flexible responses based on the availabilities of specific resources on disk or designated URIs.
Config Example
location / {
try_files $uri $uri/ /index.php;
}Ensure the fallback URI is defined; failure to do so may cause a 404 error when no files are found.
If using regular expressions, be cautious about order and combinations of matching directives.
Note that try_files stops checking as soon as it finds an existing file, which can lead to unexpected results if paths are not ordered correctly.