Serving Static Files
Harry
· 12 Sep 2026
· 10 views
Basic Static Site
server {
listen 80;
server_name example.com;
root /var/www/example;
index index.html;
location / { }
}Nginx serves index.html; URLs map directly to files under root. Try files (with fallback) using try_files:
try_files $uri $uri/ /index.html;
# 1. exact file 2. as a directory 3. fallback to index.htmlThe SPA pattern - React/Vue/Angular - needs the fallback above so client routes deep-link to index.html.
Expires and Cache Headers
Leverage the browser cache for assets with hashed filenames:
location ~* \.(css|js|png|jpg|svg|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
location / {
add_header Cache-Control "no-cache";
}Directory Listing and Index
autoindex on; # show the folder listing (use with care)
index index.html index.htm;Gzip for Text
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1024;
Key Points
- root + index is all most static sites need.
- try_files powers single-page apps serving deep URLs.
- Expires + immutable on hashed assets and gzip = fast static delivery.