basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ConfigHomelabnginx

    Static sites, SPAs, and file downloads in nginx: line-by-line configs

    Three working configs explained line by line: static sites (Astro, Hugo), single-page apps with client-side routing (React, Vue), and serving files via alias and X-Accel-Redirect. Covers hashed asset caching, blocking dotfiles, and the off-by-slash vulnerability.

    Three setups, three different configs

    Serving “static files” usually means one of three distinct patterns:

    • Prebuilt multi-page site (Astro, Hugo, Jekyll) — every URL maps to a file on disk, and missing pages should return a real 404.
    • Single-page app (React, Vue, Svelte) — routes like /users/42/settings exist only in browser JS, so nginx falls back to /index.html, while missing scripts and images still return 404.
    • File archive and protected downloads — files live outside the site root (alias), and private downloads let the app check permissions while nginx streams the bytes (X-Accel-Redirect).

    The configs below listen on port 80 to keep the focus on routing; HTTPS, TLS 1.3, and security headers are covered later in this track.

    Setup 1: static site (Astro, Hugo, Jekyll)

    The goals here are separating HTML and hashed-asset caching, blocking dotfiles (.git, .env), and leaving .well-known/ open for Let’s Encrypt validation.

    /etc/nginx/conf.d/static.example.org.conf
    server {
        listen 80;
        server_name static.example.org;
        root /var/www/static.example.org;
        index index.html;
        absolute_redirect off;

    Site root and default index file. absolute_redirect off keeps trailing-slash redirects like /docs to /docs/ relative: behind an HTTPS reverse proxy, browsers won’t get redirected to an internal http:// URL or non-standard port.

    default:absolute_redirect onindex index.html

        add_header Cache-Control "no-cache" always;
        error_page 404 /404.html;

    Cache HTML with mandatory revalidation: the browser sends If-None-Match with the ETag and gets 304 Not Modified without redownloading the body, yet picks up a fresh index.html right after a deploy. Custom 404.html is served with status 404.

    default:etag on

        location ~ /\.(?!well-known) {
            deny all;
        }

    Blocks every dotfile and hidden directory (.git, .env, .htaccess), while keeping .well-known/ accessible for Let's Encrypt challenges and standard manifests.

        location ^~ /assets/ {
            add_header Cache-Control "public, max-age=31536000, immutable" always;
            try_files $uri =404;
        }
    Key part

    Directory of build-hashed assets (app.a1b2c3.css, _astro/). ^~ prevents regex locations from matching files inside, immutable skips revalidation for a year, and try_files $uri =404 immediately returns 404 for missing files. If server defines shared security headers, include snippets/headers.conf; here too (Config anatomy).

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

    Checks in order: exact file $uri, directory $uri/ (resolving index.html), then returns 404 and triggers error_page 404 /404.html.

    Astro places hashed assets under /_astro/ instead of /assets/ — swap the prefix to location ^~ /_astro/.

    Setup 2: SPA with client-side routing (React, Vue, Svelte)

    Only two blocks change compared to a static site: unknown page routes fall back to /index.html, while missing assets still return 404.

    /etc/nginx/conf.d/spa.example.org.conf
    server {
        listen 80;
        server_name spa.example.org;
        root /var/www/spa.example.org;
        index index.html;

    Root directory of the compiled frontend (dist/ or build/).

        location ^~ /assets/ {
            add_header Cache-Control "public, max-age=31536000, immutable" always;
            try_files $uri =404;
        }
    Key part

    Keep assets in their own block with =404. Without it, a request for a removed bundle /assets/old.js falls into location /, receives index.html with Content-Type: text/html, and breaks script loading in the browser.

        location / {
            add_header Cache-Control "no-cache" always;
            try_files $uri $uri/ /index.html;
        }
    }
    Key part

    The trailing /index.html performs an internal redirect returning 200 OK so the client router renders the matching view. no-cache keeps index.html current after deploys.

    If the app needs a “Page not found” screen, the client-side router renders it: from nginx’s perspective, every route without a matching file on disk answers 200 OK with /index.html.

    Setup 3: file archive, alias, and protected downloads (X-Accel-Redirect)

    When files live outside the site root (such as /srv/archive/), use alias instead of root. When downloads are large and require auth checks, use X-Accel-Redirect: your app checks the token or session and returns an empty response with an internal path, and nginx streams the file from disk via sendfile.

    /etc/nginx/conf.d/files.example.org.conf
    server {
        listen 80;
        server_name files.example.org;
    
        location /files/ {
            alias /srv/archive/;
            autoindex on;
            autoindex_exact_size off;
            limit_rate_after 5m;
            limit_rate 500k;
        }

    Public file archive at /files/. alias replaces the /files/ prefix with /srv/archive/, so /files/report.txt reads /srv/archive/report.txt. autoindex on enables directory listings, autoindex_exact_size off prints sizes in KB/MB. limit_rate_after 5m and limit_rate 500k serve the first 5 MB at full speed, then cap the connection at 500 KB/s. Resumable downloads (Accept-Ranges: bytes) work out of the box.

    default:autoindex offlimit_rate 0 (no limit)

        location /protected/ {
            internal;
            alias /srv/private/;
        }
    Key part

    Private directory for X-Accel-Redirect. internal; blocks all external access: a direct GET /protected/book.pdf always returns 404. Only internal redirects from nginx itself can reach this block.

        location /download {
            proxy_pass http://127.0.0.1:8093;
        }
    }

    Client entry point: requests go to the app on 127.0.0.1:8093. If unauthorized, the app returns 403. If authorized, it returns 200 OK with X-Accel-Redirect: /protected/book.pdf and an empty body, handing file delivery off to nginx.

    root vs alias and the off-by-slash vulnerability

    The two directives build the filesystem path differently:

    Directive Request Resulting disk path Rule
    location /files/ + root /var/www/site; /files/report.txt /var/www/site/files/report.txt root appends the entire URI
    location /files/ + alias /srv/archive/; /files/report.txt /srv/archive/report.txt alias replaces the matched location prefix

    How to check

    1. Validate syntax and reload:
      sudo nginx -t && sudo systemctl reload nginx
    2. Static site — confirm no-cache and ETag on HTML, immutable on assets, 403 on .env, and 200 on .well-known:
      curl -sI -H "Host: static.example.org" http://127.0.0.1/ | grep -iE '^(HTTP/|cache-control|etag|accept-ranges)'
      # HTTP/1.1 200 OK
      # ETag: "6b071273-15"
      # Cache-Control: no-cache
      # Accept-Ranges: bytes
      
      curl -s -o /dev/null -w "env:%{http_code}\n" -H "Host: static.example.org" http://127.0.0.1/.env
      # env:403
      curl -s -o /dev/null -w "acme:%{http_code}\n" -H "Host: static.example.org" http://127.0.0.1/.well-known/acme-challenge/test
      # acme:200
    3. SPA — deep routes return 200 with index.html, missing assets return 404:
      curl -s -o /dev/null -w "route:%{http_code}\n" -H "Host: spa.example.org" http://127.0.0.1/users/42/settings
      # route:200
      curl -s -o /dev/null -w "asset:%{http_code}\n" -H "Host: spa.example.org" http://127.0.0.1/assets/missing.js
      # asset:404
    4. X-Accel-Redirect — direct access to /protected/ fails with 404, while /download with a valid token serves 200:
      curl -s -o /dev/null -w "direct:%{http_code}\n" -H "Host: files.example.org" http://127.0.0.1/protected/book.pdf
      # direct:404
      curl -s -o /dev/null -w "auth:%{http_code}\n" -H "Host: files.example.org" -H "X-Token: valid" http://127.0.0.1/download
      # auth:200

    If it doesn’t work

    After a deploy, browsers keep showing the old page or break on missing .js/.css files

    Cause
    HTML has a long Cache-Control (like max-age=86400), so browsers reuse the cached index.html pointing to deleted asset hashes.
    Fix
    Set Cache-Control "no-cache" always; on HTML (revalidates via ETag and returns 304), and apply max-age=31536000, immutable only to directories holding content-hashed assets.

    In a React or Vue SPA, the home page loads, but reloading /users/42 returns 404 Not Found

    Cause
    location / has try_files $uri $uri/ =404; — nginx looks for /users/42 on disk, fails to find it, and returns 404 instead of /index.html.
    Fix
    Change the fallback argument to /index.html: try_files $uri $uri/ /index.html;, while keeping try_files $uri =404; inside location ^~ /assets/.

    In an SPA, the browser console logs Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of text/html

    Cause
    A missing .js chunk fell through to location /, where try_files $uri $uri/ /index.html served HTML instead of 404.
    Fix
    Isolate /assets/ in its own location ^~ /assets/ with try_files $uri =404; so missing bundles return a real 404.

    Serving a folder via alias returns 404 for every file, and error.log shows a glued path missing a slash like /srv/archivereport.txt

    Cause
    location /files/ ends with a slash, while alias /srv/archive; does not.
    Fix
    Always pair trailing slashes on both directives: location /files/ with alias /srv/archive/;.

    A direct request to /protected/book.pdf in an X-Accel-Redirect setup returns 404, even with a valid token

    Cause
    The internal; directive blocks all direct external requests to that location — this is expected.
    Fix
    Clients always hit the app endpoint (for example /download); after verifying access, the app responds with X-Accel-Redirect: /protected/book.pdf.