🚦
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
| Command | What it does |
|---|---|
sudo nginx -t | Test the configuration for errors. |
sudo systemctl reload nginx | Apply the configuration without dropping connections. |
sudo systemctl restart nginx | Full restart (briefly drops connections). |
sudo nginx -T | Test and dump the full effective configuration. |
nginx -V | Show the version and compiled-in modules. |
sudo tail -f /var/log/nginx/error.log | Watch the error log. |
sudo tail -f /var/log/nginx/access.log | Watch the access log. |
Sites and layout
| Command | What 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/site | Disable a site without deleting its file. |
/etc/nginx/nginx.conf | Main configuration file. |
/etc/nginx/conf.d/*.conf | Drop-in configuration directory. |
Server block snippets
| Command | What 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
| Command | What 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.