How to Use try_files in Nginx: Syntax and Examples
Use the
try_files directive in Nginx to check for the existence of one or more files or directories in order, and serve the first found. If none are found, it can redirect to a fallback URI or return an error. This helps efficiently handle requests with multiple possible file locations or fallback options.Syntax
The try_files directive checks for files or directories in the order listed and serves the first one found. If none exist, it uses the last parameter as a fallback, which can be a URI or an error code.
- try_files: The directive name.
- file1, file2, ...: Paths to check, relative to the root or alias.
- fallback: URI to redirect to or error code if no files are found.
nginx
try_files file1 [file2 ...] fallback;
Example
This example tries to serve the requested URI as a file, then as a directory index, and if neither exists, it redirects to /index.php with query parameters.
nginx
server {
listen 80;
server_name example.com;
root /var/www/html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}Output
When a request comes in, Nginx first looks for a file matching the URI. If not found, it looks for a directory with that name. If still not found, it passes the request to /index.php with the original query string.
Common Pitfalls
Common mistakes include:
- Not ending the
try_filesdirective with a fallback, causing a 500 error. - Using absolute paths instead of relative paths, which can cause file not found errors.
- Misconfiguring fallback as a file path instead of a URI or error code.
Always ensure the fallback is a valid URI or error code and paths are relative to root or alias.
nginx
location / {
# Wrong: fallback is a file path, not a URI
try_files $uri $uri/ /var/www/html/index.php;
# Right: fallback is a URI
try_files $uri $uri/ /index.php?$query_string;
}Quick Reference
| Directive Part | Description | Example |
|---|---|---|
| try_files | Directive to check files in order | try_files $uri $uri/ /index.php?$query_string; |
| file1, file2 | Files or directories to check | $uri, $uri/ |
| fallback | URI or error code if none found | /index.php?$query_string or =404 |
Key Takeaways
Use try_files to efficiently serve the first existing file or directory from a list.
Always provide a fallback URI or error code as the last argument in try_files.
Paths in try_files are relative to the root or alias directive.
Avoid using absolute file system paths as fallback; use URIs or error codes instead.
Common fallback options include redirecting to index.php or returning a 404 error.