0
0
NginxHow-ToBeginner · 3 min read

How to Configure Fallback with try_files in nginx

Use the try_files directive in nginx to check for the existence of files or directories in order, and specify a fallback URI if none are found. For example, try_files $uri $uri/ /fallback.html; tries the requested URI, then its directory, and finally serves /fallback.html as a fallback.
📐

Syntax

The try_files directive tests multiple file paths or URIs in order. It takes one or more parameters followed by a fallback URI or action.

  • $uri: The requested URI as a file path.
  • $uri/: The requested URI treated as a directory.
  • Fallback URI: A file or internal location to serve if none of the previous paths exist.

The syntax looks like this:

nginx
try_files file1 [file2 ...] fallback;
💻

Example

This example shows how to serve a static file if it exists, try a directory if not, and finally serve a fallback page /404.html if neither exists.

nginx
server {
    listen 80;
    server_name example.com;

    root /var/www/html;

    location / {
        try_files $uri $uri/ /404.html;
    }

    location = /404.html {
        internal;
    }
}
Output
When a user requests a URL, nginx first looks for a matching file in /var/www/html. If not found, it checks for a directory with that name. If both fail, it serves /var/www/html/404.html as a fallback page.
⚠️

Common Pitfalls

Common mistakes when using try_files include:

  • Not specifying a fallback URI, which causes a 500 error.
  • Using an external redirect (starting with http://) instead of an internal fallback.
  • Forgetting to mark fallback locations as internal if they should not be directly accessible.

Example of a wrong and right usage:

nginx
location / {
    # Wrong: no fallback, causes error if file missing
    try_files $uri $uri/;
}

location / {
    # Right: fallback specified
    try_files $uri $uri/ /index.html;
}
📊

Quick Reference

DirectiveDescription
try_filesChecks files or URIs in order and serves the first found or fallback
$uriRequested URI as file path
$uri/Requested URI as directory
Fallback URIFile or internal location served if none found
internalMarks location as accessible only internally

Key Takeaways

Always specify a fallback URI in try_files to avoid server errors.
try_files checks each path in order and serves the first existing one.
Use internal locations for fallback pages to prevent direct access.
The fallback can be a static file or an internal redirect.
Common fallback patterns include serving index.html or a 404 page.