Nginx Cheatsheet
Serving Static Files
Use this Nginx reference while you build software engineering projects, review code, or refresh the syntax you reach for most.
Minimal Static Site
server { listen 80; server_name example.com; root /var/www/example; index index.html; location / { try_files $uri $uri/ =404; } }
try_files checks: exact file → directory (appends index) → 404.
Core Directives
| Directive | Example | What it does |
|---|---|---|
root | root /var/www/html; | Document root for the block |
alias | alias /data/img/; | Replace the matched URI prefix with this path |
index | index index.html index.htm; | Default files to serve for directory requests |
try_files | try_files $uri $uri/ /index.html; | Try paths in order, fall through to last arg |
autoindex | autoindex on; | Enable directory listing |
autoindex_exact_size | autoindex_exact_size off; | Show human-readable sizes |
autoindex_localtime | autoindex_localtime on; | Use server local time in listings |
root vs alias
# root: appends full URI to the root path location /img/ { root /var/data; # serves /var/data/img/photo.jpg } # alias: replaces the matched prefix location /img/ { alias /var/data/img/; # serves /var/data/img/photo.jpg } # With alias, always end the path in / when the location ends in /
MIME Types and Default Type
http { include /etc/nginx/mime.types; # Maps extensions → Content-Type default_type application/octet-stream; # Fallback for unknown extensions types { text/markdown md; # Add a custom type } }
Serving a Single-page App (SPA)
location / { root /var/www/app/dist; index index.html; try_files $uri $uri/ /index.html; # All 404s fall back to index.html }
Cache-Control Headers for Static Assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ { root /var/www/app; expires 1y; add_header Cache-Control "public, immutable"; access_log off; # Reduce log noise for assets }
expires value | Behaviour |
|---|---|
off | No Expires header added |
epoch | Sets Expires: Thu, 01 Jan 1970 (never cache) |
max | Sets Expires: 31 Dec 2037 (browser max) |
1y, 30d, 1h | Relative to current time |
-1 | Always expired (Cache-Control: no-cache) |
Directory Listing
location /downloads/ { root /data; autoindex on; autoindex_exact_size off; autoindex_localtime on; }
Limiting Access by IP
location /admin/ { root /var/www/app; allow 192.168.1.0/24; allow 10.0.0.5; deny all; }
Custom Error Pages
server { error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /404.html { root /var/www/errors; internal; # Not directly requestable by clients } }
Sendfile and Performance
http { sendfile on; # Zero-copy file transfer via OS (default off) tcp_nopush on; # Send headers + beginning of file in one packet tcp_nodelay on; # Disable Nagle for keepalive connections }
Enable
sendfile onfor all static file serving — it bypasses userspace copy.