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/settingsexist only in browser JS, so nginx falls back to/index.html, while missing scripts and images still return404. - 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.
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;
}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.
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;
}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;
}
}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.
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/;
}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
- Validate syntax and reload:
sudo nginx -t && sudo systemctl reload nginx - Static site — confirm
no-cacheandETagon HTML,immutableon assets,403on.env, and200on.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 - SPA — deep routes return
200withindex.html, missing assets return404: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 X-Accel-Redirect— direct access to/protected/fails with404, while/downloadwith a valid token serves200: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(likemax-age=86400), so browsers reuse the cachedindex.htmlpointing to deleted asset hashes. - Fix
- Set
Cache-Control "no-cache" always;on HTML (revalidates viaETagand returns304), and applymax-age=31536000, immutableonly 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 /hastry_files $uri $uri/ =404;— nginx looks for/users/42on 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 keepingtry_files $uri =404;insidelocation ^~ /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
.jschunk fell through tolocation /, wheretry_files $uri $uri/ /index.htmlserved HTML instead of404. - Fix
- Isolate
/assets/in its ownlocation ^~ /assets/withtry_files $uri =404;so missing bundles return a real404.
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, whilealias /srv/archive;does not.- Fix
- Always pair trailing slashes on both directives:
location /files/withalias /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 thatlocation— this is expected. - Fix
- Clients always hit the app endpoint (for example
/download); after verifying access, the app responds withX-Accel-Redirect: /protected/book.pdf.