appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

nginx cheat sheet

Free and printable

Config lives in /etc/nginx/ on most Linux systems. Always test before you reload.

Commands

sudo nginx -t
Test the configuration for errors
sudo systemctl reload nginx
Apply config without dropping connections
sudo systemctl restart nginx
Full restart
sudo nginx -T
Print the full effective configuration
sudo tail -f /var/log/nginx/error.log
Follow the error log

Server block

server { listen 80; server_name example.com; }
Answer for a host name
root /var/www/example;
Folder of static files
index index.html;
Default file for a folder
location / { try_files $uri $uri/ =404; }
Serve files or return 404
error_page 404 /404.html;
Custom error page

Reverse proxy

location / { proxy_pass http://127.0.0.1:3000; }
Forward requests to an app
proxy_set_header Host $host;
Keep the original host name
proxy_set_header X-Real-IP $remote_addr;
Pass the client IP
proxy_set_header X-Forwarded-Proto $scheme;
Tell the app if it was HTTPS

Redirects

return 301 https://$host$request_uri;
Redirect HTTP to HTTPS
return 301 https://example.com$request_uri;
Redirect to another host
rewrite ^/old/(.*)$ /new/$1 permanent;
Rewrite a path with a 301

HTTPS

listen 443 ssl;
Listen for TLS connections
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
Certificate chain
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
Private key
add_header Strict-Transport-Security "max-age=31536000" always;
HSTS header
sudo certbot --nginx -d example.com
Get a free Let's Encrypt certificate

Performance

gzip on; gzip_types text/css application/javascript application/json;
Compress text responses
location ~* \.(css|js|png|jpg|webp|svg)$ { expires 30d; }
Cache static assets for 30 days
client_max_body_size 20m;
Allow larger uploads
worker_processes auto;
One worker per CPU core

More cheat sheets