What is try_files $uri $uri/ =404; in NGINX?

In an NGINX configuration, this directive is commonly used inside a location / block to check if a requested file or directory exists on disk, and if not, return a 404 error. Here’s the directive:

location / {
    try_files $uri $uri/ =404;
}

Let’s break this down:

  • $uri – the exact path of the file requested.
  • $uri/ – checks if it’s a directory (with trailing slash).
  • =404 – if none of the above are found, NGINX directly returns a 404 Not Found error.

This logic ensures static files or directories are served only if they exist on disk.

Recommended Alternatives (Based on Use Case)

Use CaseSuggested try_files Directive
Static Websitetry_files $uri $uri/ =404;
WordPress or PHP Apptry_files $uri $uri/ /index.php?$args;
Laravel or Frameworkstry_files $uri $uri/ /index.php?$query_string;
React/SPA Frontendtry_files $uri /index.html;
Proxy to Backend AppAvoid try_files; use proxy_pass directly

Common Errors if Misused

404 Not Found for valid routes

Frontend SPA routes don’t work

PHP apps don’t load pages

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top