Tools › Cheat sheets › Web Servers & Databases › nginx
🚦

nginx cheat sheet

Everyday nginx commands and configuration snippets. Always run nginx -t before reloading so a typo does not take your site down.

Click any command to copy it.

Control

CommandWhat it does
sudo nginx -tTest the configuration for errors.
sudo systemctl reload nginxApply the configuration without dropping connections.
sudo systemctl restart nginxFull restart (briefly drops connections).
sudo nginx -TTest and dump the full effective configuration.
nginx -VShow the version and compiled-in modules.
sudo tail -f /var/log/nginx/error.logWatch the error log.
sudo tail -f /var/log/nginx/access.logWatch the access log.

Sites and layout

CommandWhat it does
sudo ln -s /etc/nginx/sites-available/site /etc/nginx/sites-enabled/Enable a site (Debian/Ubuntu layout).
sudo rm /etc/nginx/sites-enabled/siteDisable a site without deleting its file.
/etc/nginx/nginx.confMain configuration file.
/etc/nginx/conf.d/*.confDrop-in configuration directory.

Server block snippets

CommandWhat it does
server { listen 80; server_name example.com www.example.com; root /var/www/example; index index.html; }A basic static site.
location / { try_files $uri $uri/ /index.html; }Single-page app fallback.
location / { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; }Reverse proxy to an app.
return 301 https://$host$request_uri;Redirect HTTP to HTTPS (inside the port 80 server block).
client_max_body_size 50m;Allow larger uploads (default is 1 MB).
gzip on; gzip_types text/css application/javascript application/json image/svg+xml;Compress common text responses.

More snippets

CommandWhat it does
proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";Support WebSocket proxying (inside a location block).
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;Define a rate limit (in the http block), then use limit_req zone=perip burst=20;
auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd;Password-protect a location.
location ~* \.(jpg|png|css|js)$ { expires 30d; }Cache static assets in the browser.
server_tokens off;Hide the nginx version in headers and error pages.

Frequently asked questions

Why do I get 502 Bad Gateway?

nginx could not get a valid response from the upstream app. Check that the app is running and listening on the address in proxy_pass, and read the nginx error log.

Reload or restart?

Use reload after configuration changes: it applies them without dropping connections. Restart only if reload is not enough.

More Web Servers & Databases cheat sheets

🐘 PostgreSQL🐬 MySQL / MariaDB🔴 RedisAll Web Servers & Databases cheat sheets →
Copied to clipboard