patternjavascriptModerate
Nginx static file serving: optimal configuration for SPAs and assets
Viewed 0 times
nginxSPAtry_filessingle page appstatic servingcache-controlclient-side routing
Error Messages
Problem
Static file serving is slow or returns 404 for client-side routes in a single-page application because nginx does not know about client-side routing.
Solution
Configure nginx for SPAs with proper cache headers:
server {
listen 443 ssl http2;
server_name example.com;
root /var/www/myapp/dist;
index index.html;
# Cache fingerprinted assets forever
location ~* \.(js|css|png|jpg|gif|ico|woff2|svg)$ {
expires max;
add_header Cache-Control "public, max-age=31536000, immutable";
access_log off;
}
# Never cache HTML
location ~* \.html$ {
expires -1;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
# SPA fallback — serve index.html for unknown routes
location / {
try_files $uri $uri/ /index.html;
}
# API proxy
location /api/ {
proxy_pass http://127.0.0.1:3000;
}
}Why
try_files $uri $uri/ /index.html is the key for SPAs — it serves the file if it exists, then falls back to index.html so the client-side router takes over.
Gotchas
- Without the try_files fallback, refreshing any route other than / returns 404
- The order of location blocks matters — more specific patterns (regex) take priority
- http2 requires SSL — it cannot run on plain HTTP
- access_log off for assets reduces I/O on high-traffic sites significantly
Revisions (0)
No revisions yet.