TExcelTAD

root, alias & try_files

Serving files is what Nginx was built for, and three directives decide which file a URI maps to: root, alias and try_files. They are short, and each has one trap that has caused real security bugs or broken single-page apps.

root appends, alias replaces

  • root /srv/site; maps a URI to root + URI: /img/cat.png → /srv/site/img/cat.png. The location's prefix stays in the path.
  • alias /srv/pictures/; replaces the matched location prefix with the alias: in location /img/ { alias /srv/pictures/; }, /img/cat.png → /srv/pictures/cat.png.
bash · try it yourself
mkdir -p site/img pictures secret
echo "site/img/cat.png" > site/img/cat.png
echo "pictures/cat.png" > pictures/cat.png
echo "TOP SECRET"       > secret/keys.txt
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  server {
    listen 127.0.0.1:8080;
    location /img/   { root site; }
    location /pics/  { alias pictures/; }
    location /broken { alias pictures/; }       # no trailing slash on the location: the classic traversal bug
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
for u in /img/cat.png /pics/cat.png /broken/cat.png /broken../secret/keys.txt; do
  printf '%-28s -> ' "$u"; curl -s --path-as-is -w ' [%{http_code}]\n' "127.0.0.1:8080$u" | tr -d '\n'; echo
done
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
/img/cat.png                 -> site/img/cat.png [200]
/pics/cat.png                -> pictures/cat.png [200]
/broken/cat.png              -> pictures/cat.png [200]
/broken../secret/keys.txt    -> TOP SECRET [200]

The last request is the "off-by-slash" path traversal: location /broken (no trailing slash) also matches /broken.., Nginx replaces /broken with pictures/ and gets pictures/../secret/keys.txt, a file outside the folder you meant to publish. Rules of thumb:

  • If the location ends with /, the alias must end with / too, and vice versa.
  • Prefer root whenever the URI prefix can match the folder name; use alias only when it can't.
  • Never use alias in a prefix location without a trailing slash.

try_files

try_files file1 file2 … fallback; checks each candidate on disk in order and serves the first that exists; the last argument is the fallback: a URI (internal redirect), a named location (@app) or a status (=404).

Pattern Use
try_files $uri $uri/ =404; static site: the file, else the directory's index, else 404
try_files $uri /index.html; single-page app (React, Vue): unknown paths load the app, which routes in the browser
try_files $uri @app; serve static files when they exist, otherwise proxy to the application
try_files /maintenance.html $uri @app; maintenance mode switched on by creating a file
bash · try it yourself
mkdir -p www/assets
echo "<app shell>"     > www/index.html
echo "body{}"          > www/assets/app.css
cat > app.py <<'EOF'
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"app handled {self.path}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  server {
    listen 127.0.0.1:8080;
    root www;
    location /assets/ { try_files $uri =404; }                  # assets: never fall back to the app shell
    location /api/    { try_files /maintenance.html @app; }
    location /        { try_files $uri $uri/ /index.html; }      # SPA fallback
    location @app     { proxy_pass http://127.0.0.1:9000; }
  }
}
EOF
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
nginx -p "$PWD" -c nginx.conf -e stderr
show() { printf '%-22s -> %s [%s]\n' "$1" "$(curl -s "127.0.0.1:8080$1" | head -1 | tr -d '\r')" "$(curl -s -o /dev/null -w '%{http_code}' "127.0.0.1:8080$1")"; }
show /assets/app.css; show /assets/missing.js; show /orders/42; show /api/orders
echo "<h1>down for maintenance</h1>" > www/maintenance.html
show /api/orders
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill %1
/assets/app.css        -> body{} [200]
/assets/missing.js     -> <html> [404]
/orders/42             -> <app shell> [200]
/api/orders            -> app handled /api/orders [200]
/api/orders            -> <h1>down for maintenance</h1> [200]

Two details matter for single-page apps:

  • Missing assets must 404. Without the /assets/ location, /assets/missing.js would get index.html with status 200, and the browser would report a confusing syntax error ("Unexpected token '<'") instead of a missing file.
  • The fallback is an internal redirect, so /orders/42 returns the app shell with status 200 and the browser URL stays /orders/42; the app's router then renders the right page.

Maintenance mode needed no reload: try_files checks the disk on every request, so creating maintenance.html switched all /api/ traffic to it, and deleting it switches back. (With open_file_cache enabled, see Static Files, the change is noticed after the cache's validity period.) Note the status, though: the page came back with 200, which tells monitors and API clients that everything is fine. In production, answer 503 with a Retry-After header, for example if (-f $document_root/maintenance.html) { return 503; } plus error_page 503 /maintenance.html;.

try_files with proxying: the cost

Each candidate is a stat() system call. For an API location that always goes to the backend, try_files $uri @app; costs a filesystem lookup per request for nothing; use plain proxy_pass there and keep try_files for locations that really serve files.

Test yourself

location /img/ { root /srv/site; }: which file does /img/a.png map to?

  1. /srv/site/a.png
  2. /srv/site/img/a.png
  3. /srv/img/a.png
  4. /img/a.png

Why is location /files { alias /srv/files/; } dangerous?

  1. alias is deprecated
  2. Without a trailing slash, /files../x matches and maps to /srv/files/../x, outside the folder
  3. It disables caching
  4. It is slower than root

In a single-page app config, why give /assets/ its own try_files $uri =404;?

  1. Speed
  2. So that a missing JS or CSS file returns 404 instead of the HTML app shell with status 200
  3. To enable gzip
  4. Browsers require it