Nginx Config Cheat Sheet

Common Nginx config: server, location, proxy_pass, upstream, ssl, gzip, rewrite directives and snippets, with notes for ops, deployment and troubleshooting.

Directive / SnippetDescription
listen 80;Listen on a port (443 ssl for HTTPS)
server_name example.com;Virtual host domain name
root /var/www;Document root directory
index index.html;Default index file
location / { }Prefix path match block
location = /api { }Exact match (highest priority)
location ~ \.php$ { }Regex match (case-sensitive)
proxy_pass http://backend;Reverse proxy to upstream
proxy_set_header Host $host;Forward the original Host header
upstream backend { }Define a load-balancing upstream group
try_files $uri $uri/ =404;Try files in order, else 404
rewrite ^/old /new permanent;301 rewrite redirect
return 301 https://$host$request_uri;Force HTTP to HTTPS
ssl_certificate /path/fullchain.pem;SSL certificate chain path
ssl_certificate_key /path/privkey.pem;SSL private key path
gzip on;Enable gzip response compression
client_max_body_size 10m;Limit request body size
auth_basic "Restricted";Enable basic auth prompt
add_header Cache-Control "max-age=3600";Set cache-control response header
access_log /var/log/nginx/access.log;Access log path
error_log /var/log/nginx/error.log;Error log path
nginx -tTest config file syntax
nginx -s reloadReload config gracefully
nginx -s stopStop the service quickly

Frequently Asked Questions

How do I configure an Nginx reverse proxy?

Inside a `server` block, match a path with `location` and forward it with `proxy_pass http://backend;`. Usually also set `proxy_set_header Host $host;` and `proxy_set_header X-Real-IP $remote_addr;` to pass client info; the backend can be an upstream group for load balancing.

How do I force all HTTP traffic to HTTPS?

Use a `server` block listening on 80 with `return 301 https://$host$request_uri;` to 301-redirect plaintext requests to the same host over HTTPS; the HTTPS `server` block then sets `ssl_certificate` and `ssl_certificate_key`.

How do I set up load balancing with upstream?

Define `upstream backend { server 10.0.0.1:8080; server 10.0.0.2:8080; }` in the `http` block (round-robin by default). Add `weight=` for weighting or `ip_hash;` for sticky sessions, then reference it via `proxy_pass http://backend;`.

How do I apply config changes?

First run `nginx -t` to validate syntax, then `nginx -s reload` to reload gracefully (existing connections are not dropped); if Nginx is not running, start it with `nginx`. Reload avoids traffic loss compared to stop/start.