Nginx Cheat Sheet
Quick reference for Nginx configuration, common directives, reverse proxy setup, SSL, load balancing, and useful commands. Everything you need in one page.
Essential Commands
Basic Server Block
Location Blocks
Reverse Proxy
SSL / HTTPS
Performance & Caching
Load Balancing
Essential Commands
| nginx -t | Test configuration for syntax errors |
| nginx -s reload | Reload config without downtime |
| nginx -s stop | Stop immediately |
| nginx -s quit | Graceful shutdown (finish requests) |
| nginx -V | Show version and compile options |
| nginx -T | Test and dump full config |
Basic Server Block
| server { listen 80; } | Listen on port 80 (HTTP) |
| server_name example.com | Match domain name |
| root /var/www/html | Document root directory |
| index index.html index.htm | Default files to serve |
| error_page 404 /404.html | Custom error page |
| access_log /var/log/nginx/access.log | Access log location |
Location Blocks
| location / { } | Match all paths (prefix) |
| location = /exact { } | Exact match only |
| location ~* \.php$ { } | Case-insensitive regex |
| location ~ \.php$ { } | Case-sensitive regex |
| location ^~ /images/ { } | Prefix match, skip regex |
| try_files $uri $uri/ /index.html | Try file, then dir, then fallback (SPA) |
Reverse Proxy
| proxy_pass http://localhost:3000 | Forward requests to backend |
| proxy_set_header Host $host | Pass original host header |
| proxy_set_header X-Real-IP $remote_addr | Pass client IP |
| proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for | Forward chain |
| proxy_set_header X-Forwarded-Proto $scheme | Pass HTTP or HTTPS |
| proxy_read_timeout 60s | Backend response timeout |
SSL / HTTPS
| listen 443 ssl | Enable HTTPS on port 443 |
| ssl_certificate /path/to/cert.pem | SSL certificate file |
| ssl_certificate_key /path/to/key.pem | SSL private key |
| ssl_protocols TLSv1.2 TLSv1.3 | Allowed TLS versions |
| ssl_ciphers HIGH:!aNULL:!MD5 | Cipher suite selection |
| return 301 https://$host$request_uri | HTTP → HTTPS redirect |
Performance & Caching
| gzip on | Enable gzip compression |
| gzip_types text/css application/json application/javascript | Types to compress |
| expires 30d | Set cache expiration header |
| add_header Cache-Control "public, max-age=86400" | Cache control header |
| sendfile on | Efficient file serving (kernel-level) |
| tcp_nopush on | Optimize packet sending |
| worker_connections 1024 | Max connections per worker |
Load Balancing
| upstream backend { server 127.0.0.1:3000; } | Define upstream group |
| upstream backend { server a:3000; server b:3000; } | Round-robin (default) |
| upstream backend { least_conn; server a; server b; } | Least connections |
| upstream backend { ip_hash; server a; server b; } | Sticky sessions by IP |
| server a:3000 weight=3 | Weighted load balancing |
| server a:3000 backup | Backup server (used if primary down) |
Step-by-Step Guide
Read Guide →