Skip to content

How Nginx location and try_files Routing Works

How nginx picks the winning location block and how nginx try_files resolves a request to a file, a directory, or a fallback — the model behind most nginx 404 confusion.

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 location blocks and predict which one handles a given request.
  • Explain how try_files maps each argument to a filesystem path under root.
  • 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 alias versus root.

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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 at root + $uri exist? If yes, serve it.
  • $uri/ — does a directory at root + $uri exist? If yes, serve it (which then triggers index handling).
  • The last argument is special: it is either an internal redirect to another URI (re-runs location matching, e.g. /index.html or /index.php?$args) or a bare status code like =404.

Nginx location match order and try_files resolution decision tree

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

  1. 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.css serves /var/www/example/style.css if it exists; /docs/ serves the directory index if /var/www/example/docs/ exists; anything else returns 404. Confirm the config is valid:

    sudo nginx -t

    Expected output:

    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
  2. Switch the fallback to the SPA pattern. A single-page app (React, Vue, Svelte) needs every unknown path to return index.html so the client router can take over. Change only the last argument:

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

    Now /app.js and /logo.svg serve 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: =404 refuses unknown paths, /index.html rewrites them to the app shell.

  3. Add the WordPress/PHP fallback with a php-fpm handler. A PHP app needs two things: a try_files fallback that routes unknown URIs to the front controller, and a separate regex location that actually passes .php files 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 ?$args is not optional: it forwards the original query string so /?p=42 and /search?q=nginx do not lose their parameters at the fallback. Reload and confirm php-fpm is reachable in the next steps.

  4. Trace the precedence with a worked example. Take a request to /wp-admin/post.php?post=7 against 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_files in location / never runs. Now take /about-us/ (no file, no .php): no exact, no ^~, no regex matches, so the plain prefix location / wins and its try_files resolves $uri (no file), $uri/ (no directory), then the fallback /index.php?$args, which re-enters matching and this time hits the .php block. Two requests, two different winning locations, one config.

  5. 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 nginx

    A successful reload prints nothing from systemctl and returns you to the prompt. Confirm the master picked up the change:

    sudo systemctl status nginx --no-pager | head -n 3

    Expected:

    ● 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 ...
  6. 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.log

    A 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 always keyword 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.php still 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 /docs becomes a redirect to /docs/. Behind a proxy or load balancer that rewrites the Host, this can redirect to the wrong scheme or hostname; set absolute_redirect off; or fix server_name and the forwarded headers so the redirect target is correct.
  • The try_files last 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.html itself is missing under root, 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.php when the app’s front controller is actually /app.php or lives in a subdirectory.
  • alias versus root path arithmetic. With root /var/www/example;, a location /static/ maps /static/a.png to /var/www/example/static/a.png — the location prefix stays in the path. With alias /var/www/assets/;, the location prefix is stripped, so /static/a.png maps to /var/www/assets/a.png. Mixing them up produces a doubled or missing path segment and a 404 whose error-log open() line shows the wrong directory. When using alias with 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.