Intermediate
Quick reference for Nginx — config structure, server and location blocks, reverse proxy directives, upstream load balancing, TLS, gzip, caching, rate limiting, and CLI commands.
Reverse ProxyLoad BalancingTLSCaching
CLI & Files
Commands
nginx -t # test config syntax
nginx -T # test + dump full config
nginx -s reload # graceful reload
nginx -s stop # fast shutdown
nginx -s quit # graceful shutdown
nginx -v # version
systemctl reload nginx # via systemd
Paths
| Path |
Purpose |
| /etc/nginx/nginx.conf | Main config |
| /etc/nginx/conf.d/ | Included site configs |
| /var/log/nginx/ | access.log / error.log |
Server & Location
Basic server block
server {
listen 80;
server_name example.com;
root /var/www/example;
index index.html;
location / { try_files $uri $uri/ =404; }
}
Location precedence
| Modifier |
Match |
= | Exact (highest) |
^~ | Prefix, skip regex |
~ / ~* | Regex (case-sens / insens) |
| (none) | Longest prefix (lowest) |
Reverse Proxy
Proxy pass + headers
location /api/ {
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-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
}
Load Balancing
Upstream
upstream backend {
least_conn; # or ip_hash; default = round-robin
server 10.0.0.11:3000 weight=3;
server 10.0.0.12:3000;
server 10.0.0.13:3000 backup;
keepalive 32;
}
Methods
| Directive |
Strategy |
| (default) | Round-robin |
least_conn | Fewest active conns |
ip_hash | Sticky by client IP |
TLS / HTTP/2
server {
listen 443 ssl;
http2 on;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=63072000" always;
}
# redirect http -> https
server { listen 80; return 301 https://$host$request_uri; }
Gzip, Cache, Rate Limit
Gzip
gzip on;
gzip_comp_level 5;
gzip_types text/css application/json application/javascript;
Proxy cache
# http {}
proxy_cache_path /var/cache/nginx keys_zone=zone1:10m max_size=1g;
# location {}
proxy_cache zone1;
proxy_cache_valid 200 10m;
add_header X-Cache-Status $upstream_cache_status;
Rate limit
# http {}
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
# location {}
limit_req zone=api burst=20 nodelay;
Useful Variables
| Variable |
Value |
$host | Request host header |
$uri | Normalized request path |
$request_uri | Full original URI + query |
$remote_addr | Client IP |
$scheme | http or https |