Nginx Cheatsheet
This cheatsheet provides a comprehensive and practical reference for Nginx commands and configuration. It covers basic commands, configuration files, server blocks, location & rewrite, security, logs, command combos, and more. Use it to boost your productivity in web server management and automation.
Service Management
sudo systemctl start nginxStart Nginx service
sudo systemctl stop nginxStop Nginx service
sudo systemctl restart nginxRestart Nginx service
sudo systemctl reload nginxReload configuration
sudo systemctl status nginxCheck service status
sudo systemctl enable nginxEnable at boot
Configuration
nginx -tTest configuration syntax
nginx -TTest and dump configuration
nginx -VShow version and build options
nginx -s reloadReload configuration
nginx -s stopFast shutdown
nginx -s quitGraceful shutdown
Basic Server Block
server {
listen 80;
server_name example.com;
root /var/www/html;
}Basic HTTP server
listen 80 default_server;Default server for port 80
listen [::]:80;Listen on IPv6
server_name example.com www.example.com;Multiple server names
server_name *.example.com;Wildcard server name
server_name ~^www\d+\.example\.com$;Regex server name
HTTPS Server
listen 443 ssl http2;HTTPS with HTTP/2
ssl_certificate /path/to/cert.pem;SSL certificate path
ssl_certificate_key /path/to/key.pem;SSL key path
ssl_protocols TLSv1.2 TLSv1.3;Allowed TLS versions
ssl_prefer_server_ciphers on;Prefer server ciphers
ssl_session_cache shared:SSL:10m;SSL session cache
Location Matching
location / { ... }Prefix match (lowest priority)
location = /exact { ... }Exact match (highest priority)
location ^~ /images/ { ... }Prefix match, stop regex search
location ~ \.php$ { ... }Case-sensitive regex
location ~* \.(jpg|png)$ { ... }Case-insensitive regex
location @named { ... }Named location
💡 Priority: = > ^~ > ~ or ~* > prefix
Common Directives
root /var/www/html;Document root
alias /var/www/files/;Replace location path
index index.html index.php;Default index files
try_files $uri $uri/ /index.php?$query_string;Try files in order
autoindex on;Enable directory listing
return 301 https://$host$request_uri;Redirect to HTTPS
Reverse Proxy
proxy_pass http://localhost:3000;Proxy to backend
proxy_set_header Host $host;Pass original host
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;Forward protocol
proxy_http_version 1.1;Use HTTP/1.1
WebSocket Proxy
proxy_set_header Upgrade $http_upgrade;WebSocket upgrade header
proxy_set_header Connection "upgrade";WebSocket connection
proxy_read_timeout 86400;Long timeout for WS
Load Balancing
upstream backend {
server 127.0.0.1:8001;
server 127.0.0.1:8002;
}Basic upstream
upstream backend {
least_conn;
server ...;
}Least connections
upstream backend {
ip_hash;
server ...;
}IP hash (sticky)
server 127.0.0.1:8001 weight=3;Weighted server
server 127.0.0.1:8001 backup;Backup server
server 127.0.0.1:8001 down;Mark server down
Security Headers
add_header X-Frame-Options "SAMEORIGIN" always;Prevent clickjacking
add_header X-Content-Type-Options "nosniff" always;Prevent MIME sniffing
add_header X-XSS-Protection "1; mode=block" always;XSS protection
add_header Strict-Transport-Security "max-age=31536000" always;HSTS header
add_header Content-Security-Policy "default-src 'self'" always;CSP header
add_header Referrer-Policy "strict-origin-when-cross-origin" always;Referrer policy
Access Control
allow 192.168.1.0/24;Allow IP range
deny all;Deny all others
auth_basic "Restricted";Enable basic auth
auth_basic_user_file /etc/nginx/.htpasswd;Password file
satisfy any;Allow OR deny rules
Rate Limiting
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;Define rate limit zone
limit_req zone=one burst=5 nodelay;Apply rate limit
limit_conn_zone $binary_remote_addr zone=addr:10m;Connection limit zone
limit_conn addr 10;Max 10 connections per IP
Caching
proxy_cache_path /tmp/cache levels=1:2 keys_zone=my_cache:10m;Define cache path
proxy_cache my_cache;Enable proxy cache
proxy_cache_valid 200 60m;Cache 200 responses for 60m
proxy_cache_use_stale error timeout;Serve stale on error
add_header X-Cache-Status $upstream_cache_status;Show cache status
Browser Caching
expires 30d;Expire in 30 days
expires max;Maximum expiry
add_header Cache-Control "public, no-transform";Cache control header
etag on;Enable ETag
Compression
gzip on;Enable gzip
gzip_vary on;Add Vary header
gzip_min_length 1000;Min size to compress
gzip_types text/plain text/css application/json application/javascript;Types to compress
gzip_comp_level 6;Compression level (1-9)
Optimization
sendfile on;Enable sendfile
tcp_nopush on;Optimize packet sending
tcp_nodelay on;Disable Nagle's algorithm
keepalive_timeout 65;Keep-alive timeout
client_max_body_size 100M;Max upload size
Log Configuration
access_log /var/log/nginx/access.log;Access log path
error_log /var/log/nginx/error.log warn;Error log with level
access_log off;Disable access log
access_log /var/log/nginx/access.log combined buffer=512k flush=1m;Buffered logging
Custom Log Format
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent';Define log format
log_format json escape=json '{"time":"$time_iso8601","ip":"$remote_addr"}';JSON log format
access_log /var/log/nginx/access.log main;Use custom format
Request Variables
$hostHost from request line or Host header
$uriCurrent URI (normalized)
$request_uriOriginal request URI with args
$args / $query_stringQuery string
$request_methodHTTP method (GET, POST, etc.)
$schemeRequest scheme (http/https)
Client Variables
$remote_addrClient IP address
$remote_portClient port
$http_user_agentUser-Agent header
$http_refererReferer header
$http_cookieCookie header
$http_x_forwarded_forX-Forwarded-For header
Response Variables
$statusResponse status code
$body_bytes_sentBytes sent to client
$request_timeRequest processing time
$upstream_response_timeUpstream response time
$upstream_cache_statusCache status (HIT/MISS)
Quick Reference
nginx -t
nginx -s reload
/etc/nginx/nginx.conf
/etc/nginx/sites-enabled/
Categories
- Basic Commands
Start, stop, reload, test, and manage Nginx service.
- Configuration Files
Main config, includes, and site-specific configuration files.
- Server Block Examples
Common server block (virtual host) configuration patterns.
- Location & Rewrite
Location matching, URL rewriting, directory listing, and try_files.
- Security & Optimization
Headers, limits, access control, and performance tuning.
- Logs & Monitoring
Log files, log levels, and real-time monitoring.
- Command Combos
Powerful multi-step workflows and advanced usage patterns for real-world scenarios.
Features
- Quick search functionality
- Organized by categories
- Clear command descriptions
- Common and advanced use cases covered
- Easy to copy commands
- Responsive design
- Perfect for quick reference