SearchBook a call

JOURNAL / Engineering

Nginx root, alias, and the off-by-slash path traversal bug

How Nginx root resolves URIs, why alias off-by-slash causes path traversal, server-level inheritance, SPA fallback traps, and curl verification.

Written by Dexter and Anish Kr Singh. This is a practical systems engineering guide to how Nginx resolves filesystem paths with root and alias, why a single missing trailing slash opens a classic path traversal vulnerability, and how to harden and verify static and reverse-proxy configurations.

Few Nginx directives look as deceptively harmless as root and alias. Both map an incoming HTTP request URI to a directory on disk. Both appear in five-line tutorials. Yet misunderstanding the exact string math between root, alias, location, and try_files is responsible for one of the longest-lived misconfiguration vulnerabilities on the web—the off-by-slash path traversal—as well as an endless stream of broken SPA routes, silent 404s, and leaked .env files.

The fix is not memorising superstition. It is understanding the exact resolution model Nginx executes on every request.

Exact URI resolution semantics: root vs alias

When Nginx selects a location block to serve a static file, root and alias compute the filesystem path in two fundamentally different ways:

  • root appends the entire normalized request $uri directly to the configured root path: filesystem_path = <root> + <$uri>
  • alias strips the matched location prefix from $uri and appends only the remaining suffix to the configured alias path: filesystem_path = <alias> + (<$uri> without matched location prefix)

Look at how identical-looking configurations map the same incoming URI to completely different files on disk:

Location block Directive Incoming $uri Resolved filesystem path
location /static/ root /var/www; /static/app.js /var/www/static/app.js
location /static/ root /var/www/static; /static/app.js /var/www/static/static/app.js (doubled!)
location /static/ alias /var/www/assets/; /static/app.js /var/www/assets/app.js
location /static alias /var/www/static/; /static/app.js /var/www/static//app.js
location /static alias /var/www/static/; /static../.env /var/www/static/../.env → /var/www/.env

That last row is where production secrets walk out the front door.

The classic off-by-slash path traversal bug

Consider a configuration that shows up constantly in production configs, Docker images, and Stack Overflow answers:

# VULNERABLE: location has NO trailing slash, alias HAS a trailing slash
location /static {
    alias /var/www/app/static/;
}

At first glance, /static/logo.png works fine—Nginx strips /static, leaving /logo.png, concatenates /var/www/app/static/ + /logo.png, collapses the double slash, and serves /var/www/app/static/logo.png. Smoke tests pass.

Now trace what happens when a client sends a raw HTTP request with .. immediately after /static—no slash between them:

GET /static../.env HTTP/1.1
Host: example.com

Walk through Nginx’s request pipeline step by step:

  1. URI normalization happens before location matching. Nginx checks /static../.env for dot-segments (/../). There is no /../ segment here: the path component is literally static.., which is a valid ordinary directory name in RFC 3986. Nginx leaves $uri untouched as /static../.env.
  2. Prefix location matching runs. location /static performs a raw prefix match against /static../.env. Because /static../.env begins with the seven characters /static, it matches!
  3. alias strips the matched prefix. Nginx removes /static from /static../.env, leaving ../.env.
  4. Concatenation creates a brand-new traversal segment. Nginx appends ../.env to /var/www/app/static/, yielding: /var/www/app/static/../.env
  5. The OS resolves the parent directory. The kernel opens /var/www/app/.env and Nginx hands back your database credentials and signing keys with 200 OK.

Even worse, GET /static../config/secrets.yml or GET /static../.git/HEAD reads any sibling file inside /var/www/app/ that the Nginx worker user can read.

Why root avoids this entire class of bug

Compare that with rewriting the same mapping using root (or matching trailing slashes strictly if alias is unavoidable):

# SAFE: root appends the full normalized $uri
server {
    listen 80;
    server_name example.com;
    root /var/www/app;

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

Trace both attack vectors against this root configuration:

  • GET /static/../.env: Nginx normalizes dot-segments before location selection, collapsing the URI to /.env. It never enters location /static/, and our hidden-file rule (covered below) blocks /.env with 404.
  • GET /static../.env: Does not match location /static/ because of the trailing slash. Even if the location were written location /static with root /var/www/app, root appends the full $uri without stripping anything, producing /var/www/app/static../.env—a lookup for a literal non-existent directory named static.., never a .. parent traversal.

If you genuinely must use alias (for example, mounting /downloads/ from /mnt/storage/public/ where the directory name does not match the URI prefix), enforce a strict rule: both the location prefix and the alias target must end with a trailing slash:

# SAFE alias: trailing slash on BOTH location and alias
location /downloads/ {
    alias /mnt/storage/public/;
}

With a trailing slash on location /downloads/, /downloads../.env never matches the prefix, and /downloads/../.env is normalized to /.env before the location block ever sees it.

Root inheritance: why server-level root beats location-level root

Nginx’s official pitfalls guide has repeated one piece of advice for over a decade: set root once inside the server block, not inside location /.

Here is the anti-pattern that breaks subtly at scale:

# BAD: root buried inside location /
server {
    server_name example.com;

    location / {
        root /var/www/app/public;
        try_files $uri $uri/ =404;
    }

    location /images/ {
        expires 30d;
        # BUG: no root inherited from location /!
        # Falls back to Nginx's compiled-in default (often /usr/share/nginx/html)
    }
}

In Nginx, directives inherit downward (http → server → location), never sideways between sibling location blocks. Putting root inside location / leaves every sibling location (/images/, location ~ \.css$, error_page locations) silently falling back to Nginx’s built-in default prefix. You end up copy-pasting root into five blocks, and the first time someone updates the deploy path in four of them, one route starts serving 404s.

Setting root once at the server level eliminates duplication and makes every location inherit a single source of truth. Only override root inside a specific location when that prefix genuinely maps to a separate filesystem mount whose on-disk directory name already matches the URI prefix.

How try_files, $document_root, and SPA fallbacks interact

Once root is set cleanly at the server level, three interactions still trip teams up in production.

$document_root vs $realpath_root

Inside any request, $document_root holds the resolved root (or alias) directory string literally as configured. $realpath_root resolves all symbolic links in that path. If you deploy atomically by flipping a symlink (/var/www/current -> /var/www/releases/2026-11-20), passing $document_root to PHP-FPM or an upstream can cause opcode caches to serve stale files across release flips; $realpath_root guarantees the upstream sees the immutable release directory.

try_files with alias vs root

Historically, combining alias with try_files inside prefix or regex location blocks has been a notorious source of edge-case bugs (including the famous long-standing Nginx trac #97 behavior around fallback URIs and trailing directory checks). With root, try_files $uri $uri/ /index.html; behaves predictably because $uri always maps cleanly against $document_root. Prefer root whenever try_files is in play.

The SPA fallback trap

Single-page applications routinely configure:

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

The bug appears as soon as a deployment rotates hashed asset bundles or a client requests a mistyped API route. If /assets/app.9f2a1c.js no longer exists on disk, try_files silently falls through to /index.html and returns 200 OK with Content-Type: text/html. Browsers fail with a cryptic MIME-type syntax error (Unexpected token '<'), CDNs cache the HTML error page under the .js URL, and monitoring sees 200s instead of 404s.

Isolate static assets and API prefixes explicitly with =404 or proxy_pass so only genuine document routes fall back to /index.html:

location /assets/ {
    try_files $uri =404;
    expires 1y;
    add_header Cache-Control "public, immutable" always;
    add_header X-Content-Type-Options "nosniff" always;
}

location /api/ {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Notice that add_header X-Content-Type-Options "nosniff" always; is repeated inside location /assets/. That is deliberate: Nginx’s add_header directive does not merge across scopes. Adding any add_header inside a location block wipes out every add_header inherited from the parent server block.

A hardened static and reverse-proxy server block

Putting all of these pieces together yields a clean, production-grade server block that avoids alias traversal, blocks symlink escapes, hides dotfiles without breaking Let’s Encrypt ACME HTTP-01 challenges, and keeps SPA fallbacks honest:

server {
    listen 80;
    server_name example.com;

    # Single server-level root inherited by all locations
    root /var/www/app/dist;
    index index.html;

    # Prevent directory listings and symlink escapes outside $document_root
    autoindex off;
    disable_symlinks if_not_owner from=$document_root;

    # Baseline security header (re-declare in any location that uses add_header)
    add_header X-Content-Type-Options "nosniff" always;

    # Block dotfiles (.env, .git, .htaccess) while allowing /.well-known/ for ACME
    location ~ /\.(?!well-known).* {
        deny all;
        return 404;
    }

    # Immutable static assets: never fall back to index.html on 404
    location ^~ /assets/ {
        try_files $uri =404;
        expires 1y;
        add_header Cache-Control "public, immutable" always;
        add_header X-Content-Type-Options "nosniff" always;
    }

    # Upstream API: keep reverse-proxy traffic completely separate from disk paths
    location ^~ /api/ {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # SPA fallback for document routes only
    location / {
        try_files $uri $uri/ /index.html;
    }
}

Two small details are worth noting in that block:

  • location ^~ /assets/ stops regex location checks once the prefix matches, preventing a stray regex block from hijacking static files.
  • disable_symlinks if_not_owner from=$document_root; checks path components starting from $document_root, so an atomic deploy symlink at /var/www/current still works while an untrusted symlink planted inside the web root cannot pivot out to /etc/passwd. (If you do not rely on symlinks inside the tree at all, disable_symlinks on from=$document_root; is stricter still.)

Verifying configs with nginx -t and curl –path-as-is

Never trust an Nginx config by visual inspection alone—and never test path traversal with plain curl, because curl normalizes .. segments client-side before sending the request over the wire. Always pass --path-as-is.

Start by validating syntax and inspecting the full merged configuration (which catches stray alias directives hidden in include files):

# Syntax check
sudo nginx -t

# Dump the full resolved config and audit every alias and root directive
sudo nginx -T | grep -En '^\s*(server_name|location|root|alias|disable_symlinks|add_header)\b'

Then run concrete HTTP probes against the live listener:

# 1. Off-by-slash alias traversal probe (MUST return 404, never 200)
curl --path-as-is -sS -o /dev/null -w "%{http_code}\n" \
  https://example.com/assets../.env

# 2. Dot-segment escape probe (MUST return 404 or normalized blocked path)
curl --path-as-is -sS -o /dev/null -w "%{http_code}\n" \
  https://example.com/assets/../../etc/passwd

# 3. Dotfile probe (MUST return 404)
curl -sS -o /dev/null -w "%{http_code}\n" \
  https://example.com/.git/HEAD

# 4. Missing static asset probe (MUST return 404, NOT 200 text/html)
curl -sS -D - -o /dev/null \
  https://example.com/assets/does-not-exist.js | grep -Ei '^(HTTP/|content-type:|x-content-type-options:)'

# 5. Confirm /.well-known/ is not accidentally blocked by the dotfile regex
curl -sS -o /dev/null -w "%{http_code}\n" \
  https://example.com/.well-known/acme-challenge/probe

On the hardened config above, probes 1 through 4 all return 404 (with X-Content-Type-Options: nosniff present on the response headers), and no missing asset ever masquerades as 200 OK HTML.

Closing note

This article was written by Dexter and Anish Kr Singh as part of our ongoing systems engineering notes at Velofy. The entire Nginx static-path discipline boils down to four habits: prefer root over alias, set root once at the server level, match trailing slashes strictly whenever alias is unavoidable, and verify every boundary with nginx -T and curl --path-as-is before shipping.

← All journal entries