When a request reaches nginx, exactly one location block handles it, and nginx chooses that block by a fixed priority order — not by the order the blocks appear in your config. Inside the winning block, try_files walks its arguments left to right, testing each one against the filesystem under root, and hands the request to the first argument that resolves; the final argument is a fallback that either serves a file (an internal redirect, like /index.html) or returns a status such as =404. Almost every “why is nginx returning 404?” case comes down to one of two things: a different location won than you expected, or try_files tested a path that does not exist on disk. This guide makes both mechanisms concrete so you can predict which block answers and what it looks for.
What you’ll accomplish
- Read a set of
locationblocks and predict which one handles a given request. - Explain how
try_filesmaps each argument to a filesystem path underroot. - Configure the three common patterns: a strict static root, the SPA fallback, and the WordPress/PHP fallback.
- Use
nginx -t, the error log, and a debug header to prove which handler answered. - Recognize the failure modes — regex beating a prefix, trailing-slash redirects, a missing fallback target, and
aliasversusroot.
Prerequisites
- Nginx 1.24 or newer (
nginx -v), which covers all current stable and mainline behavior described here. - The ability to edit server blocks under
/etc/nginx/and to reload nginx. - A document root you control (for example
/var/www/example) with at least one real file in it.
How it works
Nginx resolves a request URI to a location in a defined precedence order, and only after a location wins does anything inside it — including try_files — run.
The matching order for a given normalized URI is:
- Exact match —
location = /path. If the URI equals the string exactly, this wins immediately and nginx stops searching. Use it for hot single paths like= /or= /favicon.ico. - Prefix match with
^~—location ^~ /assets/. Nginx tracks the longest matching prefix. If that longest prefix carries the^~modifier, nginx uses it and skips regex matching entirely. - Regex —
location ~ \.php$(case-sensitive) or~*(case-insensitive). Nginx tests regex locations in the order they appear in the file and uses the first that matches. A regex match beats a plain prefix match. - Plain prefix —
location /. If no exact, no^~, and no regex matched, nginx falls back to the longest plain prefix.location /is the catch-all because every URI shares that prefix.
The rule that trips people up: a regex location (step 3) outranks a plain prefix location (step 4), even when the prefix looks more specific. location ~ \.php$ will win over location /wp-content/ for a request to /wp-content/plugin/thing.php, because regex is checked before plain prefixes are finalized.
Once a location wins, try_files decides what to serve. Each argument except the last is treated as a path relative to root (or alias), and nginx checks the filesystem:
$uri— does a file atroot + $uriexist? If yes, serve it.$uri/— does a directory atroot + $uriexist? If yes, serve it (which then triggersindexhandling).- The last argument is special: it is either an internal redirect to another URI (re-runs location matching, e.g.
/index.htmlor/index.php?$args) or a bare status code like=404.
The mental model: location matching picks the handler; try_files picks the file. A 404 can come from either stage — the wrong handler, or a handler whose files are not where it looked.
Step-by-step
-
Start from a strict static baseline. This root serves real files and returns a clean 404 when nothing matches, instead of leaking a directory listing or falling through to an app.
server { listen 80; server_name example.com; root /var/www/example; location / { try_files $uri $uri/ =404; } }With this block, a request to
/style.cssserves/var/www/example/style.cssif it exists;/docs/serves the directory index if/var/www/example/docs/exists; anything else returns404. Confirm the config is valid:sudo nginx -tExpected output:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful -
Switch the fallback to the SPA pattern. A single-page app (React, Vue, Svelte) needs every unknown path to return
index.htmlso the client router can take over. Change only the last argument:location / { try_files $uri $uri/ /index.html; }Now
/app.jsand/logo.svgserve their real files, but/dashboard/settings— which has no file on disk — falls through to/index.html. The difference from the baseline is one token:=404refuses unknown paths,/index.htmlrewrites them to the app shell. -
Add the WordPress/PHP fallback with a php-fpm handler. A PHP app needs two things: a
try_filesfallback that routes unknown URIs to the front controller, and a separate regexlocationthat actually passes.phpfiles to php-fpm.server { listen 80; server_name blog.example.com; root /var/www/wordpress; index index.php index.html; location / { try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/run/php/php8.3-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } }The
?$argsis not optional: it forwards the original query string so/?p=42and/search?q=nginxdo not lose their parameters at the fallback. Reload and confirm php-fpm is reachable in the next steps. -
Trace the precedence with a worked example. Take a request to
/wp-admin/post.php?post=7against the block above. Nginx first checks for an exact= /wp-admin/post.php(none), then^~prefixes (none), then regex:~ \.php$matches, so that block wins and the request goes straight to php-fpm —try_filesinlocation /never runs. Now take/about-us/(no file, no.php): no exact, no^~, no regex matches, so the plain prefixlocation /wins and itstry_filesresolves$uri(no file),$uri/(no directory), then the fallback/index.php?$args, which re-enters matching and this time hits the.phpblock. Two requests, two different winning locations, one config. -
Validate the syntax, then reload. Never reload without testing first — a broken config aborts the reload and can leave the old workers running with stale behavior.
sudo nginx -t && sudo systemctl reload nginxA successful reload prints nothing from
systemctland returns you to the prompt. Confirm the master picked up the change:sudo systemctl status nginx --no-pager | head -n 3Expected:
● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; preset: enabled) Active: active (running) since ... -
Read the error log and add a debug header when a 404 surprises you. The error log names the exact filesystem path nginx tested, which instantly tells you whether the problem is the location or the file.
sudo tail -n 20 /var/log/nginx/error.logA
try_files-driven 404 looks like this:2026/07/20 10:14:02 [error] 991#991: *12 open() "/var/www/example/dashboard/settings" failed (2: No such file or directory), client: 203.0.113.9, server: example.com, request: "GET /dashboard/settings HTTP/1.1", host: "example.com"To confirm which location answered, add a temporary header inside the block you suspect, reload, and read it back:
location / { add_header X-Debug-Path "root-slash-block" always; try_files $uri $uri/ /index.html; }The
alwayskeyword makes the header appear even on error responses. Remove it once you have your answer.
Validate it works
Curl specific paths and watch which handler answers. For the static baseline, an existing file returns 200 and a missing one returns 404:
curl -sI http://example.com/style.css | head -n 1
curl -sI http://example.com/nope.css | head -n 1
HTTP/1.1 200 OK
HTTP/1.1 404 Not Found
For the SPA block, a missing path should return 200 (the shell), not 404:
curl -sI http://example.com/dashboard/settings | head -n 1
HTTP/1.1 200 OK
For the PHP block, confirm the debug header reports the block you expect, and that the access log records the request while the error log stays quiet:
curl -sI http://blog.example.com/ | grep -i x-debug-path
sudo tail -n 5 /var/log/nginx/access.log
A 200 in the access log with no matching error.log line means the request resolved cleanly through the location and try_files you intended.
Troubleshooting
- A regex location beats the prefix you expected. You wrote
location /wp-content/ { ... }to protect a directory, but requests to/wp-content/x.phpstill hit php-fpm. That is correct precedence — regex outranks plain prefix. If you truly need the prefix to win over regex, give it the^~modifier:location ^~ /wp-content/, which stops nginx before regex matching runs. - A trailing-slash redirect surprises you. When
$uri/matches a directory, nginx issues a 301 to add the trailing slash before serving the index. A request to/docsbecomes a redirect to/docs/. Behind a proxy or load balancer that rewrites the Host, this can redirect to the wrong scheme or hostname; setabsolute_redirect off;or fixserver_nameand the forwarded headers so the redirect target is correct. - The
try_fileslast argument points at a file that does not exist.try_files $uri /index.html;returns a hard 404 (or 500 in some builds) if/index.htmlitself is missing underroot, because the fallback has nothing to serve. Confirm the target exists:ls -l /var/www/example/index.html. For the PHP pattern, the equivalent mistake is a fallback to/index.phpwhen the app’s front controller is actually/app.phpor lives in a subdirectory. aliasversusrootpath arithmetic. Withroot /var/www/example;, alocation /static/maps/static/a.pngto/var/www/example/static/a.png— the location prefix stays in the path. Withalias /var/www/assets/;, the location prefix is stripped, so/static/a.pngmaps to/var/www/assets/a.png. Mixing them up produces a doubled or missing path segment and a 404 whose error-logopen()line shows the wrong directory. When usingaliaswith a regex location, you must supply the full replacement path yourself.- The PHP fallback drops the query string.
try_files $uri $uri/ /index.php;— without?$args— routes the request but discards?post=7, so pagination, search, and preview links silently break. Always write the fallback as/index.php?$args.
When this is the wrong approach
location and try_files cover file resolution and simple front-controller fallbacks. They are the wrong tool once your logic is genuinely conditional — matching on headers, cookies, or several variables at once. For that, reach for the map directive to build a variable, and named locations (location @fallback) to keep the flow readable, as covered in nginx map module redirects; piling if blocks into a location is the classic way to get surprising behavior. Application-level routing — which controller runs, which middleware fires — belongs in the app, not in nginx; try_files should only get the request to the front controller, not decide what the app does with it. And if your team spends more time fighting nginx’s precedence rules than shipping, a proxy with automatic, label-driven routing like Caddy or Traefik may fit your conventions better; the trade-off is less fine-grained control over exactly how each path resolves. For the precise semantics of every modifier and directive here, the nginx HTTP core module documentation is the authoritative reference, and once a request is being proxied, proxying WebSockets through nginx picks up where file resolution ends.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.