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 Case | Suggested try_files Directive |
---|---|
Static Website | try_files $uri $uri/ =404; |
WordPress or PHP App | try_files $uri $uri/ /index.php?$args; |
Laravel or Frameworks | try_files $uri $uri/ /index.php?$query_string; |
React/SPA Frontend | try_files $uri /index.html; |
Proxy to Backend App | Avoid 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