This page is config-centric, not command-centric. nginx's operational surface is mostly about getting the config right: the commands (
nginx OSS vs nginx Plus: active health checks (
nginx -t, nginx -s reload) are few and simple. Most of what bites you in production is a subtle config mistake: wrong upstream keepalive settings, missing proxy headers, rate limit zones sized too small, or TLS misconfiguration. Config snippets are the primary content here.
nginx OSS vs nginx Plus: active health checks (
health_check directive), sticky sessions, and the live activity monitor require nginx Plus. OSS passive health checks (via max_fails/fail_timeout) are shown throughout. Plus-only features are marked.
cross-cutting: know these before anything else
essential commands
nginx -t
nginx -T
nginx -s reload
nginx -s quit
nginx -v && nginx -V
# -t: test config; -T: dump full config; reload: zero-downtime
always validate before reload
nginx -t && nginx -s reload
systemctl reload nginx
nginx -t 2>&1 | grep -E "error|warn"
# NEVER: nginx -s reload without -t first
# a bad reload leaves old workers serving stale config
# check: ps aux | grep nginx (old workers linger)
config structure
/etc/nginx/nginx.conf # main
/etc/nginx/conf.d/*.conf # included sites
/etc/nginx/snippets/ # reusable blocks
nginx -T | grep "include"
# verify all includes are loading from expected paths
# nginx -T dumps the full merged config. Use for debugging
proxy_pass gotcha
# With trailing slash: strips location prefix:
location /api/ { proxy_pass http://backend/; }
# /api/users → http://backend/users
# Without trailing slash: passes full URI:
location /api/ { proxy_pass http://backend; }
# /api/users → http://backend/api/users
# trailing slash on proxy_pass is the #1 nginx gotcha
green = shell command
yellow = nginx config snippet
| Pattern | Phase | Config / Commands | Notes |
|---|---|---|---|
| config validation | config |
nginx -t
nginx -T
nginx -T | grep -E "server_name|listen|upstream"
nginx -t && systemctl reload nginx
curl -sv http://localhost/health 2>&1 | grep -E "< HTTP|< X-"
ss -tlnp | grep nginx
|
nginx -T dumps the complete merged configuration: the definitive way to debug include ordering and see exactly what nginx is running. Always run nginx -t before reload; a failed reload leaves the old config running, which may not be obvious. ss -tlnp | grep nginx confirms which ports nginx is actually listening on after reload. |
| minimal API gateway config | config |
server {
listen 443 ssl;
server_name api.example.com;
location /api/v1/ {
proxy_pass http://backend_v1/;
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_connect_timeout 5s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
}
|
Always set all four proxy headers: backends that log the real IP need X-Forwarded-For; backends behind multiple proxies need X-Forwarded-Proto to know if the original request was HTTPS. Explicit timeouts are required: nginx defaults (60s) are too high for most APIs where you'd rather fail fast and let the client retry. |
| worker / connection tuning | config |
# nginx.conf: http/events blocks:
worker_processes auto; # one per CPU core
worker_rlimit_nofile 65535; # match system ulimit
events {
worker_connections 4096; # per worker
use epoll; # Linux only
multi_accept on;
}
http {
keepalive_timeout 65;
keepalive_requests 1000;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
}
|
Max concurrent connections = worker_processes × worker_connections. worker_rlimit_nofile must match or exceed the OS file descriptor limit (ulimit -n). multi_accept on accepts all pending connections at once rather than one per event loop cycle: necessary under high load. tcp_nodelay on disables Nagle's algorithm: critical for low-latency API responses. |
| upstream block patterns | upstream |
upstream backend_v1 {
least_conn; # or: round_robin (default), ip_hash
server 10.0.0.1:8080 weight=3;
server 10.0.0.2:8080 weight=1;
server 10.0.0.3:8080 backup; # only used when others fail
keepalive 32; # idle keepalive connections per worker
keepalive_requests 100;
keepalive_timeout 60s;
}
# in location block, add:
proxy_http_version 1.1;
proxy_set_header Connection "";
|
keepalive in the upstream block + proxy_http_version 1.1 + clearing the Connection header is the complete pattern for upstream connection reuse: all three directives are required. Without this, nginx opens a new TCP connection to the backend for every request. backup servers receive traffic only when all primary servers fail. |
| passive health checks | upstream |
upstream backend {
server 10.0.0.1:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.2:8080 max_fails=3 fail_timeout=30s;
}
# in location block: what counts as a failure:
proxy_next_upstream error timeout http_500 http_502 http_503;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 10s;
# active health checks (nginx Plus only):
health_check interval=10s fails=3 passes=2 uri=/health;
|
Passive health checks (OSS): after max_fails failures within fail_timeout the server is marked unavailable for fail_timeout seconds. proxy_next_upstream defines what response codes trigger a retry on the next upstream. proxy_next_upstream_tries caps retries, without a cap, a failed cluster triggers retries across all backends amplifying load. |
| dynamic upstream via resolver | upstream |
# resolve upstream hostnames dynamically (useful in containers/K8s):
resolver 127.0.0.53 valid=30s ipv6=off;
resolver_timeout 5s;
server {
set $backend "http://my-service.namespace.svc.cluster.local:8080";
location /api/ {
proxy_pass $backend;
}
}
# using a variable in proxy_pass forces re-resolution per request
# without resolver, nginx resolves once at startup and caches forever
|
In Kubernetes, using a static upstream hostname with no resolver causes nginx to cache the IP at startup: when the pod IP changes (common after restarts), nginx sends traffic to dead IPs until reload. The variable + resolver pattern forces DNS re-resolution, keeping nginx aligned with the current service endpoint. Set valid to a short TTL. |
| rate limiting zones | rate limiting |
# in http block: define zones:
limit_req_zone $binary_remote_addr zone=per_ip:10m rate=10r/s;
limit_req_zone $http_x_api_key zone=per_key:10m rate=100r/s;
limit_req_zone $server_name zone=per_server:10m rate=1000r/s;
# in location block: apply:
limit_req zone=per_ip burst=20 nodelay;
limit_req zone=per_key burst=50 nodelay;
limit_req_status 429;
limit_req_log_level warn;
|
burst allows short spikes above the rate; nodelay processes burst requests immediately rather than queuing them (queue = latency spike). Zone size: 1MB stores ~16,000 IP states; 10MB covers most API deployments. Rate by API key ($http_x_api_key) allows per-client limits independently of IP: clients behind NAT share the same IP but not the same key. |
| connection limiting | rate limiting |
# limit concurrent connections (separate from request rate):
limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;
limit_conn_zone $server_name zone=conn_per_server:10m;
server {
limit_conn conn_per_ip 10; # max 10 concurrent from one IP
limit_conn conn_per_server 1000; # max 1000 concurrent to this vhost
limit_conn_status 503;
limit_conn_log_level warn;
}
|
limit_conn limits simultaneous open connections, not request rate: distinct from limit_req. A single slow HTTP/1.1 client with 10 open connections consumes limit_conn budget. Use both together: limit_req for request throughput, limit_conn for Slowloris-style connection exhaustion attacks. Per-server limit protects the backend from overload. |
| API key auth | auth |
# simple map-based API key validation:
map $http_x_api_key $api_client {
default ""; # unknown key → empty string
"key-abc123" "client-a";
"key-def456" "client-b";
}
server {
location /api/ {
if ($api_client = "") { return 401; }
proxy_set_header X-API-Client $api_client;
proxy_pass http://backend/;
}
}
|
Map-based API key validation is O(1) lookup: performant for hundreds of keys. Reload nginx after adding/removing keys. For large key sets or dynamic key management, delegate to auth_request pointing to an auth service. Pass the resolved client identity as a header so the backend knows who called it. |
| JWT via auth_request | auth |
server {
location /api/ {
auth_request /auth;
auth_request_set $auth_user $upstream_http_x_auth_user;
proxy_set_header X-Auth-User $auth_user;
proxy_pass http://backend/;
error_page 401 = @error401;
}
location = /auth {
internal;
proxy_pass http://auth-service/validate;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
location @error401 { return 401 '{"error":"unauthorized"}'; }
}
|
auth_request delegates authentication to a subrequest: your auth service validates the JWT and returns 200/401. auth_request_set captures response headers from the auth service and makes them available for injection into the upstream request. internal on the auth location prevents direct external access. proxy_pass_request_body off avoids forwarding the request body to the auth service unnecessarily. |
| basic auth | auth |
htpasswd -c /etc/nginx/.htpasswd alice
htpasswd /etc/nginx/.htpasswd bob
openssl passwd -apr1 mypassword
location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://admin-backend/;
}
|
Basic auth is appropriate for internal admin interfaces, not public APIs: credentials are base64-encoded, not encrypted, so HTTPS is required. htpasswd uses bcrypt by default in modern versions; use openssl passwd -apr1 to generate APR1-MD5 for compatibility with older htpasswd files. Never use basic auth on an HTTP endpoint. |
| TLS configuration | tls / mtls |
server {
listen 443 ssl; # add http2 for HTTP/2
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
ssl_prefer_server_ciphers off; # TLS 1.3 negotiates ciphers
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_stapling on;
ssl_stapling_verify on;
add_header Strict-Transport-Security "max-age=63072000" always;
}
|
TLS 1.0 and 1.1 are broken: drop them. The cipher list prioritises ECDHE forward-secrecy suites. ssl_prefer_server_ciphers off is correct for TLS 1.3 which has its own cipher negotiation. ssl_session_cache dramatically reduces TLS handshake overhead for repeated connections. OCSP stapling reduces client-side certificate validation latency. |
| mTLS (mutual TLS) | tls / mtls |
# require client certificate on /api/internal/:
server {
ssl_client_certificate /etc/nginx/ssl/ca.pem;
ssl_verify_client optional; # or: on (required), off
ssl_verify_depth 2;
location /api/internal/ {
if ($ssl_client_verify != SUCCESS) { return 403; }
proxy_set_header X-SSL-Client-CN $ssl_client_s_dn_cn;
proxy_set_header X-SSL-Client-Cert $ssl_client_escaped_cert;
proxy_pass http://internal-backend/;
}
}
|
ssl_verify_client optional allows both mTLS and non-mTLS clients on the same server. Use if ($ssl_client_verify != SUCCESS) per-location to enforce it selectively. Pass the client CN and cert to backends so they can perform identity-based authorization. ssl_verify_depth 2 allows certificates signed by intermediate CAs in a two-level hierarchy. |
| Let's Encrypt (certbot) | tls / mtls |
certbot --nginx -d api.example.com
certbot renew --dry-run
certbot renew --pre-hook "nginx -t" --post-hook "nginx -s reload"
certbot certificates
openssl x509 -in /etc/letsencrypt/live/api.example.com/cert.pem -noout -dates
|
--nginx plugin modifies nginx config automatically and handles reload. Use --pre-hook "nginx -t" to abort renewal if the config is invalid before the reload. Check expiry with openssl x509 -noout -dates to confirm the cert that's actually loaded, not just what certbot reports. Certbot installs a systemd timer for auto-renewal. Verify it's running with systemctl status certbot.timer. |
| access log format | observability |
http {
log_format json_combined escape=json
'{"time":"$time_iso8601",'
'"method":"$request_method",'
'"uri":"$request_uri",'
'"status":$status,'
'"bytes_sent":$bytes_sent,'
'"request_time":$request_time,'
'"upstream_response_time":"$upstream_response_time",'
'"upstream_addr":"$upstream_addr",'
'"http_referer":"$http_referer",'
'"http_x_forwarded_for":"$http_x_forwarded_for"}';
access_log /var/log/nginx/access.log json_combined;
}
|
JSON access logs are machine-parseable by any log aggregator without a custom grok pattern. upstream_response_time is the backend latency; request_time includes nginx processing + backend: the difference is nginx overhead. escape=json escapes special characters in variable values, preventing log injection. Pipe through jq for immediate local analysis. |
| stub_status + metrics | observability |
server {
listen 8080; # internal only. Do not expose publicly
allow 10.0.0.0/8;
deny all;
location /nginx_status {
stub_status;
}
}
curl -s http://localhost:8080/nginx_status
# output: Active connections, accepts, handled, requests, Reading/Writing/Waiting
# Waiting (keepalive idle) high → reduce keepalive_timeout
# handled < accepts → connections being dropped
|
stub_status is OSS nginx's basic metrics endpoint: exposes active connections and request counters. Restrict to internal networks only. Waiting count = idle keepalive connections; if this dominates Active connections, reduce keepalive_timeout. nginx Plus exposes a full JSON API at /api/ with per-upstream server stats, zone metrics, and cache hit rates. |
| log analysis patterns | observability |
# top 503/502 URIs (last hour):
awk '$9 ~ /50[23]/' /var/log/nginx/access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head -20
# slowest requests (JSON log):
cat /var/log/nginx/access.log | jq -r 'select(.request_time > 1) | [.request_time, .uri, .status] | @tsv' | sort -rn | head -20
# requests per second (last minute):
awk -v d="$(date -d '1 minute ago' '+%d/%b/%Y:%H:%M')" '$4 > "["d' /var/log/nginx/access.log | wc -l
# top client IPs hitting 429:
awk '$9 == 429 {print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
|
These patterns work on both default combined log format (awk) and JSON log format (jq). Top 429 IPs helps tune rate limit zones: if the same legitimate client is being rate-limited, the zone rate or burst needs adjusting. Top error URIs during an incident points to which endpoint is failing, not just that something is failing. |
No patterns match this filter.