The first time I touched Nginx in production, I copied a config off a blog, restarted the service, and watched a 502 error page take down half a million users for nine minutes. The config "looked right." It wasn't. Nginx doesn't fail loud-it fails quiet, then explodes under the first real load. This is the guide I wish I'd had: not the official docs rewritten in friendlier words, but the actual mental model and the actual configs that have survived Black Friday traffic and a poorly-timed certificate renewal.
Nginx is deceptively simple. The syntax is small, the directives look readable, and you can have a working reverse proxy in five lines. But "working" and "production-correct" are separated by about forty details that nobody puts in the same place: worker counts, upstream timeouts, TLS session resumption, header pass-through, gzip vs brotli, real client IP, health checks, graceful reloads, and the dozen ways proxy_pass can surprise you. We're going to cover all of them.
Why Nginx and Not Caddy, HAProxy, or Apache
Let me be honest about the trade-offs. Nginx is not always the right answer. Sometimes it's just the answer you already have.
| Web server / proxy | Async model | Config style | TLS automation | Sweet spot |
|---|---|---|---|---|
| Nginx | Event-driven, single-thread workers | Declarative, verbose | Manual or via certbot | Reverse proxy, TLS termination, static files at scale |
| Caddy | Event-driven | Concise, sane defaults | Built-in ACME | Small projects, zero-config HTTPS |
| HAProxy | Event-driven, single-process | Declarative, very precise | Manual | Pure L4/L7 load balancing at high RPS |
| Apache | Process/thread per request (MPM) | Verbose, modular | Manual | Legacy apps, .htaccess per-directory config |
I reach for Nginx when I need one tool doing TLS, reverse proxy, static files, rate limiting, and compression. I reach for Caddy on small projects where I want to never think about certificates again. HAProxy goes in front when I have serious L7 routing needs (multiple upstream algorithms, sticky sessions with consistent hashing, deep observability). Apache I haven't started a new project on in years, but I still maintain inherited ones.
If you're reading this, you've probably already picked Nginx. So let's make sure it's configured to survive.
Prerequisites
- A Linux box (Ubuntu 22.04 or 24.04 LTS is what I'll assume). Debian and RHEL are fine; paths differ slightly.
- Root or a user in the
sudogroup. Nginx binds to ports 80 and 443 by default, which need privileges. - A domain name pointing at the box. Without it, TLS via Let's Encrypt is awkward.
-
curl,openssl, andhtopinstalled. You'll live in these tools. - Basic familiarity with
systemctlandjournalctl. If you've never runjournalctl -u nginx -f, you will today.
I'm going to assume you have at least one backend service running on 127.0.0.1:8000. Swap in your own port. The Nginx patterns here don't care whether that's a FastAPI app, a Node server, or a Go binary.
What an Nginx Request Actually Does
Before any config, understand the flow. Nginx is event-driven: one master process spawns N worker processes, each worker handles thousands of concurrent connections via an event loop (epoll on Linux). There are no threads per request. This is why Nginx scales-worker count is fixed, and each worker multiplexes connections.
CodeCopy [client request:443]
|
v
+------------------------------------------------------+
| nginx master (runs as root, owns :80 and :443) |
| | |
| +-- worker 1 (uid=www-data, epoll loop) |
| +-- worker 2 (uid=www-data, epoll loop) |
| +-- worker N (uid=www-data, epoll loop) |
| |
| per-connection lifecycle: |
| accept -> TLS handshake -> read req -> |
| proxy_pass to upstream -> read response -> |
| write response -> keepalive or close |
+------------------------------------------------------+
|
v
[upstream: 127.0.0.1:8000]
The master process is the only thing running as root. Workers drop to www-data (or nginx on RHEL). When you systemctl reload nginx, the master sends SIGHUP to workers, they finish in-flight requests, then exit. New workers pick up the new config. No dropped connections, no downtime. This is the single most important thing to internalize: reload, don't restart.
Installation
Ubuntu's default Nginx is fine for most people. If you need a newer mainline version (recommended for new features like HTTP/3 and improved TLS), use the official repo.
BashCopy
shell
Option A: distro version (stable, slightly behind)
sudo apt update
sudo apt install -y nginx
Option B: official mainline (recommended for new projects)
sudo apt install -y curl gnupg2 ca-certificates lsb-release debian-archive-keyring
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
| sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/mainline/ubuntu $(lsb_release -cs) nginx" \
| sudo tee /etc/apt/sources.list.d/nginx.list
sudo apt update
sudo apt install -y nginx
Verify
nginx -v
systemctl status nginx
plaintext
For Docker, prefer nginxinc/nginx-unprivileged so the worker runs as a non-root user. The default nginx image works, but binding ports below 1024 as root inside a container is a smell.
BashCopy
shell
docker run -d --name nginx \
-p 8080:8080 \
-v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro \
-v $(pwd)/conf.d:/etc/nginx/conf.d:ro \
nginxinc/nginx-unprivileged:1.27
markdown
Directory Layout That Scales
The default Nginx install dumps everything in /etc/nginx/nginx.conf and /etc/nginx/conf.d/*.conf. That works for two vhosts. Past five, it becomes a mess. Use the Debian-style sites-available/sites-enabled pattern everywhere.
CodeCopy
plaintext
/etc/nginx/
nginx.conf # global: workers, events, http block defaults
conf.d/ # package defaults, leave alone
sites-available/ # one file per vhost, full configs
api.example.com.conf
app.example.com.conf
staging.example.com.conf
sites-enabled/ # symlinks to sites-available
api.example.com.conf -> ../sites-available/api.example.com.conf
snippets/
tls.conf # shared TLS directives
security-headers.conf # shared headers
proxy.conf # shared proxy_pass directives
auth/
htpasswd.admin # basic auth files
plaintext
Enable and disable vhosts with symlinks. This gives you atomic toggles and lets you keep staged configs in sites-available without serving them.
BashCopy
shell
Enable a vhost
sudo ln -s /etc/nginx/sites-available/api.example.com.conf \
/etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
Disable without deleting
sudo rm /etc/nginx/sites-enabled/api.example.com.conf
sudo nginx -t && sudo systemctl reload nginx
markdown
Always run nginx -t before reload. It catches syntax errors without affecting the running config. If -t fails, the reload silently does nothing-production keeps running on the old config. This has saved me more times than I can count.
The Globalnginx.conf
This is the file that sets workers, the event model, and default HTTP behavior. Here's a production-tested baseline:
nginxCopy
nginx
user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;
pid /run/nginx.pid;
events {
worker_connections 16384;
multi_accept on;
use epoll;
}
http {
# Basics
default_type application/octet-stream;
server_tokens off; # hide version in headers and error pages
# Logging
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct="$upstream_connect_time" '
'urt="$upstream_response_time"';
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
error_log /var/log/nginx/error.log warn;
# Performance
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65s;
keepalive_requests 1000;
reset_timedout_connection on;
# Client body limits (tune for your app)
client_max_body_size 25m;
client_body_buffer_size 128k;
client_body_timeout 30s;
client_header_timeout 30s;
send_timeout 30s;
# Compression
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 4;
gzip_min_length 1024;
gzip_types
text/plain text/css text/xml text/javascript
application/javascript application/json application/xml
application/rss+xml application/atom+xml image/svg+xml;
# Includes
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/.conf;
include /etc/nginx/sites-enabled/;
}
markdown
A few things worth explaining:
-
worker_processes automatches the number of CPU cores. Setting it manually to higher than core count doesn't help and can hurt. -
worker_connections 16384is per worker. Total concurrent connections =worker_processes * worker_connections. With 4 cores, that's 65,536. Make sureworker_rlimit_nofileand the systemulimit -nare at least that high. -
multi_accept ontells each worker to grab all pending connections from the listen queue at once instead of one at a time. Under bursty traffic this matters. -
server_tokens offremoves the Nginx version from headers and error pages. Security through obscurity? Yes, but it also stops automatic scanners that fingerprint versions. -
gzip_comp_level 4is the sweet spot. Level 9 buys you ~2% smaller responses at 5x the CPU. Don't.
Reverse Proxy: The Heart of It
Most Nginx installs exist to put something in front of a backend. Here's the minimal correct reverse proxy:
nginxCopy
nginx
/etc/nginx/sites-available/api.example.com.conf
upstream api_backend {
server 127.0.0.1:8000 max_fails=3 fail_timeout=30s;
keepalive 32;
}
server {
listen 80;
listen [::]:80;
server_name api.example.com;
# Redirect everything to HTTPS
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name api.example.com;
# TLS (see snippet below)
include snippets/tls.conf;
# Security headers (see snippet below)
include snippets/security-headers.conf;
# Real client IP (if behind a CDN, set real_ip_recursive and trusted ranges)
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
# ... add your CDN ranges here
real_ip_header CF-Connecting-IP;
# Logging per vhost
access_log /var/log/nginx/api.example.com.access.log main;
error_log /var/log/nginx/api.example.com.error.log warn;
# Health check endpoint (don't proxy to backend)
location = /healthz {
access_log off;
return 200 "ok\n";
add_header Content-Type text/plain;
}
# Main app
location / {
proxy_pass http://api_backend;
include snippets/proxy.conf;
}
}
plaintext
And the snippets that make this clean:
nginxCopy
nginx
/etc/nginx/snippets/proxy.conf
proxy_http_version 1.1;
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_set_header X-Forwarded-Host $host;
Critical: enable keepalive to upstream
proxy_set_header Connection "";
Timeouts (the #1 cause of 502s)
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
Buffering (default on; turn off for streaming/SSE)
proxy_buffering on;
proxy_buffer_size 16k;
proxy_buffers 8 32k;
proxy_busy_buffers_size 64k;
markdown
The single biggest mistake I see: people omit proxy_http_version 1.1 and proxy_set_header Connection "". Without HTTP/1.1 to the upstream, Nginx opens a new TCP connection for every request. With keepalive 32 in the upstream block and HTTP/1.1, Nginx reuses 32 long-lived connections. On a 1,000 RPS service, this is the difference between 1,000 upstream connections and 32. Your backend will thank you.
TLS Termination With Let's Encrypt
Get certificates via certbot. It modifies your Nginx config automatically and sets up renewal.
BashCopy
shell
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d api.example.com -d www.api.example.com \
--redirect --agree-tos -m you@example.com --no-eff-email
plaintext
The shared TLS snippet:
nginxCopy
nginx
/etc/nginx/snippets/tls.conf
ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/api.example.com/chain.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
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_session_cache shared:SSL:50m;
ssl_session_timeout 1d;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
resolver 1.1.1.1 8.8.8.8 valid=300s;
resolver_timeout 5s;
markdown
A few non-obvious points:
-
ssl_prefer_server_ciphers offis now the recommended default. With TLS 1.3, the client picks the cipher. With TLS 1.2, letting the client pick is safer because the client knows what hardware acceleration it has. -
ssl_session_tickets offdisables session tickets because they're a known forward-secrecy weakness if the ticket key leaks. Session cache (ssl_session_cache) is enough. -
ssl_stapling onenables OCSP stapling, so the server includes a signed OCSP response in the handshake. Without it, every client does a separate OCSP lookup, which adds latency and creates a privacy leak (the CA learns which IPs are visiting your site). - The
resolverdirective is needed because Nginx needs to resolve the OCSP responder hostname at runtime, not at config-load time.
Test your config with the Qualys SSL Labs test. Aim for A+. If you get a B, it's almost always because you didn't disable TLS 1.0/1.1.
Load Balancing Strategies
Nginx load-balances by default with round-robin. Other strategies exist; pick the right one for your workload.
| Strategy | Directive | When to use | Caveat |
|---|---|---|---|
| Round-robin | (default) | Homogeneous backends, stateless apps | Doesn't consider load |
| Least connections | least_conn; | Backends with varying response times | Slightly more CPU per request |
| IP hash | ip_hash; | Sticky sessions without cookies | Doesn't work behind IPv6 dual-stack or CDN |
| Generic hash | hash $request_uri; | Cache-friendly routing | Rehashing storms when membership changes |
| Random | random two least_conn; | At extreme scale, reduces lock contention | Rarely needed below 50k RPS |
nginxCopy
nginx
upstream api_backend {
least_conn;
server 10.0.0.10:8000 weight=3 max_fails=3 fail_timeout=30s;
server 10.0.0.11:8000 weight=1 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8000 weight=1 max_fails=3 fail_timeout=30s backup;
keepalive 64;
}
markdown
-
weight=Nmakes one server get N times more requests. Useful when one box is beefier. -
backupmeans "only use this if all primaries are down." Great for a maintenance page server. -
max_fails=3 fail_timeout=30sis passive health checking: if Nginx sees 3 failed connections in 30 seconds, it marks the server down for 30 seconds. This is the default Nginx behavior-no active health checks without the paid Nginx Plus.
For active health checks without paying for Plus, run a sidecar (a small script or a tool like nginx-upsync-module) that polls /healthz on each backend and updates the upstream config. Or just accept passive checks-they're usually fine.
Rate Limiting and Connection Limiting
Nginx can rate-limit at two levels: per-IP connection count and per-IP request rate. Define zones in the http block, apply them in server or location blocks.
nginxCopy
nginx
In http {}
limit_req_zone $binary_remote_addr zone=api_rl:10m rate=20r/s;
limit_conn_zone $binary_remote_addr zone=api_cl:10m;
In server {} or location {}
location /api/ {
limit_req zone=api_rl burst=40 nodelay;
limit_conn api_cl 10;
proxy_pass http://api_backend;
include snippets/proxy.conf;
}
markdown
-
rate=20r/sallows 20 requests per second per IP, sustained. -
burst=40allows a spike of 40 above the rate, queued. -
nodelaymeans burst requests are served immediately, not throttled. Without it, burst requests are delayed to match the rate. -
limit_conn api_cl 10caps simultaneous connections per IP at 10. Stops a single client opening 1,000 slow connections.
The 10m zone size holds ~160,000 unique IPs (10 megabytes / 64 bytes per entry). If you have more users than that, bump the size.
A subtle gotcha: rate limiting by $binary_remote_addr doesn't work if Nginx is behind a CDN-every request looks like it's coming from the CDN's IP. Use $http_x_forwarded_for (split to last hop) or a CDN-specific header like $http_cf_connecting_ip instead. Better yet, rate-limit at the CDN edge.
Caching Responses
For endpoints that can tolerate staleness (public read endpoints, static JSON, rendered HTML), Nginx's proxy cache is a cheat code. One config can take 90% of load off your backend.
nginxCopy
nginx
In http {}
proxy_cache_path /var/cache/nginx/api
levels=1:2
keys_zone=api_cache:50m
max_size=5g
inactive=30m
use_temp_path=off;
In location {}
location /api/public/ {
proxy_cache api_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_valid any 5s;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://api_backend;
include snippets/proxy.conf;
}
markdown
The magic is proxy_cache_use_stale + proxy_cache_background_update: when a cached item expires, Nginx serves the stale version while fetching a fresh one in the background. Users never see the delay. If your backend is down, Nginx keeps serving stale cache for inactive duration. This is how you survive a backend outage without anyone noticing.
proxy_cache_lock on makes sure that when 100 requests arrive for the same uncached URL, only one goes to the backend-the rest wait for it to fill the cache. Without this, a cache miss becomes a thundering herd.
X-Cache-Status header values: MISS, BYPASS, EXPIRED, STALE, UPDATING, REVALIDATED, HIT. Log it. Alert on sustained high MISS rates-something is wrong with your cache key.
WebSocket and Server-Sent Events
WebSockets need the Upgrade headers. SSE needs buffering disabled. Get either wrong and you'll spend a day wondering why connections drop at 60 seconds.
nginxCopy
nginx
WebSocket
location /ws/ {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 3600s; # keep WS open for an hour
proxy_send_timeout 3600s;
}
Server-Sent Events (text/event-stream)
location /events/ {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off; # critical: don't buffer SSE
proxy_cache off;
proxy_read_timeout 3600s;
chunked_transfer_encoding on;
}
plaintext
The SSE gotcha is brutal: with proxy_buffering on (the default), Nginx holds the entire response in memory until the upstream closes the connection. SSE never closes. Your client sees nothing, ever. Set proxy_buffering off for SSE endpoints specifically.
For WebSocket, the long proxy_read_timeout matters because there's no traffic on the wire between messages. Default 60s kills idle WS connections.
Worker Tuning and System Limits
Nginx workers don't help if the OS can't open enough file descriptors. Every connection is a file descriptor. Every upstream connection is another. So a worker with 16,384 connections needs ~32,768 file descriptors.
BashCopy
shell
Check current limits
ulimit -n
cat /proc/$(pgrep -f 'nginx: master')/limits | grep "Max open files"
Raise them system-wide (/etc/security/limits.conf)
- soft nofile 65535
- hard nofile 65535
And for systemd services (this is what actually applies to nginx)
sudo systemctl edit nginx
Add:
[Service]
LimitNOFILE=65535
Apply
sudo systemctl daemon-reload
sudo systemctl restart nginx
plaintext
Also check the somaxconn and net.core.somaxconn for the listen backlog. Default 4096 is usually fine, but if you ever see SYN flooding or dropped connections under load, bump it:
BashCopy
shell
echo "net.core.somaxconn = 65535" | sudo tee -a /etc/sysctl.d/99-nginx.conf
echo "net.ipv4.tcp_max_syn_backlog = 65535" | sudo tee -a /etc/sysctl.d/99-nginx.conf
sudo sysctl -p /etc/sysctl.d/99-nginx.conf
markdown
Production Considerations
Scaling
Nginx scales vertically well-more cores, more workers. Past 8-10 cores per box, you start hitting diminishing returns because the listen socket becomes a contention point. At that point, scale horizontally with multiple Nginx boxes behind a load balancer (AWS ALB, Cloudflare, HAProxy).
Performance
- Enable
brotlifor better compression than gzip on text. Same CPU, 15-20% smaller for HTML/JS. - Use HTTP/2 (or HTTP/3 if you have a recent mainline Nginx and a QUIC-capable client base).
- Disable access logging for high-traffic static endpoints, or log only errors. Logging is I/O.
- Put
sendfile onandtcp_nopush onfor static files.
Security
- Run workers as a non-root user (
www-dataornginx). Never as root. -
server_tokens off. - Disable unused modules when compiling from source. The distro build is fine for 95% of cases.
- Use a WAF in front (Cloudflare, AWS WAF) for L7 attack mitigation. Nginx itself isn't a WAF.
- Rotate access logs to prevent disk fill. Use
logrotate.
Monitoring
Export Nginx metrics with nginx-prometheus-exporter or ngx_http_stub_status_module (built-in but limited). The important metrics:
| Metric | What it tells you | Alert if |
|---|---|---|
nginx_connections_active | Current active connections | Sustained > 80% of worker_connections |
nginx_connections_waiting | Idle keepalive connections | Growing trend (clients not closing) |
nginx_requests_total | Total requests handled | Sudden drop (traffic loss) |
nginx_upstream_response_time | Backend latency | p99 > 1s |
nginx_upstream_5xx | Backend errors | Any sustained rate |
Logging
Structured logging to stdout (not files) is the modern approach when running in containers or systemd-journald. Use JSON logs for easier ingestion by ELK or Loki:
nginxCopy
nginx
log_format json escape=json '{'
'"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"bytes":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_response_time":"$upstream_response_time",'
'"upstream_connect_time":"$upstream_connect_time",'
'"upstream_addr":"$upstream_addr",'
'"user_agent":"$http_user_agent"'
'}';
access_log /var/log/nginx/access.log json;
markdown
Deployment
- Use
nginx -tbefore every reload. Always. - Use
systemctl reload nginx, notrestart. Reload is graceful. - For zero-downtime binary upgrades, use the in-place upgrade process: spawn a new master with the new binary, send
WINCHto the old master (workers exit gracefully), thenQUITthe old master. The official docs cover this. I've done it once in 10 years; usually just take a 30-second maintenance window. - Deploy configs via your config management (Ansible, Salt, Chef, Pulumi). Don't SSH in to edit files.
Common Mistakes
Mistake 1: restart instead of reload. Restart drops all in-flight connections. Reload is graceful. If you restart in a deploy script, your users see 502s.
Mistake 2: Forgetting proxy_http_version 1.1 and Connection "". Without these, every request opens a new TCP connection to the upstream. Backend connection churn goes through the roof. Detect by checking backend-side connection counts-if you see one new connection per request, this is why.
Mistake 3: Setting worker_processes to a fixed number unrelated to cores. If you have 8 cores and worker_processes 4, you're leaving half your CPU idle. Use auto.
Mistake 4: Not raising worker_rlimit_nofile and LimitNOFILE. Workers can't open enough FDs and silently start refusing connections. Detect with nginx_connections_active plateauing at the FD limit.
Mistake 5: TLS termination at Nginx but unencrypted traffic to backend over a public network. If Nginx and backend are on different hosts, traffic between them is plaintext. Either run them on the same box, use a private network, or terminate TLS at the backend too (with proxy_pass https://...).
Mistake 6: Putting client_max_body_size 0 (unlimited). Users upload 10GB files. Your server OOMs. Set a sane limit per route.
Mistake 7: Using if directives in location blocks. Nginx's if is famously buggy ("If Is Evil" is an official wiki page). Use try_files, map, or separate location blocks instead.
Mistake 8: Not handling large Host header / X-Forwarded-For chains. Set large_client_header_buffers to a reasonable size; otherwise a malicious client can send 8KB headers and exhaust worker memory.
Troubleshooting Real Production Issues
Symptom: Intermittent 502 Bad Gateway.
First, check the upstream. curl -v http://127.0.0.1:8000/healthz from the Nginx box. If that fails, your backend is down. If it works, check error.log-you'll see connect() failed or upstream prematurely closed connection. The first means the backend refused the connection (port not listening, firewall). The second means the backend accepted the connection but crashed mid-response. For the second, increase proxy_read_timeout and look at backend logs.
Symptom: 504 Gateway Timeout under load.
Your backend is too slow. Either fix the backend or raise proxy_read_timeout. Don't just raise the timeout to mask a slow backend-users will give up before Nginx does.
Symptom: WebSocket connections drop at exactly 60 seconds.
Default proxy_read_timeout is 60s. Set it to 3600s (or longer) for WebSocket locations.
Symptom: HTTPS works in browser, fails in curl.
Usually SNI. Old curl versions or specific clients don't send SNI. Add server_name to the server block and make sure your cert matches. Test with curl -v https://api.example.com and look for the TLS handshake.
Symptom: Certbot renewal succeeds but old cert is still served.
Nginx caches the cert file descriptor. After renewal, run systemctl reload nginx or use certbot's --deploy-hook "systemctl reload nginx".
Symptom: nginx -t says OK but reload doesn't pick up changes.
You edited a file in sites-available but didn't symlink to sites-enabled. Or you edited the right file but nginx -t validated a different one. Check /etc/nginx/sites-enabled/.
Symptom: High CPU, low traffic.
Almost always gzip_comp_level 9. Drop to 4. Or you have if blocks that re-evaluate per request.
Symptom: Disk fills up from logs.
logrotate not configured, or per-vhost logs not rotated. Add a drop-in /etc/logrotate.d/nginx if it doesn't exist.
Best Practices, Testing, and CI/CD
- Version control your Nginx configs.
/etc/nginxshould be a git repo or managed by your IaC tool. Manual edits are how config drift happens. - Test configs in CI. Run
nginx -t -c /path/to/nginx.confin CI against every PR. Withdocker run nginx:1.27 nginx -t -c ...you don't even need Nginx installed. - Lint with
gixy(a static analyzer for Nginx configs). It catches the common footguns: missingserver_tokens off, SSRF via$host, etc. - Canary changes. Deploy config changes to one box first. Watch metrics for 30 minutes. Then roll out.
- Use
nginx -Tto dump the effective config. This is the config after all includes are resolved. Invaluable for debugging "which location block is actually matching?" - Tag your Docker image with the Nginx version, not
latest.nginx:1.27notnginx:latest. Reproducibility matters.
YAMLCopy
yaml
.github/workflows/nginx-lint.yml
name: nginx-lint
on: [pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate Nginx config run: | docker run --rm \ -v ${{ github.workspace }}/nginx:/etc/nginx:ro \ nginx:1.27 nginx -t
- name: Run gixy run: | pip install gixy gixy /etc/nginx/nginx.conf || true
Cost Considerations, Alternatives, and Comparison
Nginx itself is free (open source BSD-2). The cost is operational: the boxes you run it on, the time you spend tuning, and the cost of mistakes.
| Option | License | Cost | Sweet spot |
|---|---|---|---|
| Nginx OSS | BSD-2 | Free | Most production reverse proxy needs |
| Nginx Plus | Commercial | $2,500+/yr/instance | Active health checks, dynamic upstream, dashboard |
| Caddy | Apache 2.0 | Free | Small projects, zero-config HTTPS |
| HAProxy | GPL2 | Free | Pure L7 LB at extreme RPS |
| Traefik | MIT | Free | Container-native, auto-discovery |
| AWS ALB | Managed | $0.0225/hr + $0.008/GB | When you don't want to run your own |
| Cloudflare | Managed | $0-200+/mo | CDN + edge proxy + DDoS |
For most teams running services on their own infra: Nginx OSS. For teams that have moved to Kubernetes: an Ingress controller (Nginx Ingress, Traefik, or Caddy). For teams fully on AWS: ALB + CloudFront, skip running your own Nginx.
Real-World Use Cases
E-commerce checkout. Nginx in front of a FastAPI checkout service, with proxy_cache for product pages (10 min TTL) and no cache for /cart and /checkout. Cache hit rate ~70% on product pages. Backend load drops 60%.
Multi-tenant SaaS. One Nginx box per region, routing by Host header to the right tenant's backend. Wildcard cert via Let's Encrypt. Rate limiting per IP at 100r/s burst 200.
Static site delivery. Nginx serving S3-synced static files. sendfile on, tcp_nopush on, gzip + brotli, 1-year cache headers with hash-based filenames. TTFB under 20ms.
API gateway. Nginx in front of 12 microservices. Each service gets its own location block, its own upstream, its own rate limit zone. JWT validation via auth_request to a dedicated auth service.
WebSocket fanout. Nginx load-balancing across 4 Node.js WebSocket servers. ip_hash for stickiness (or hash $http_authorization if you have a session token). proxy_read_timeout 3600s. 50k concurrent connections sustained.
Conclusion
Nginx is one of those tools that rewards understanding. The config syntax is small enough to learn in an afternoon; the production behavior takes years to internalize. The configs in this article are the ones I've shipped to production and watched survive real traffic. Steal them, modify them, and make them yours.
The recurring theme: Nginx fails quiet. Reloads are silent. Timeouts are silent. Cache misses are silent. The way you survive is by instrumenting everything-log cache status, log upstream timings, alert on connection plateaus, and run nginx -t before every deploy. Do that, and Nginx becomes the boring, reliable piece of your infrastructure it's supposed to be.
Originally published on Mango Developer.
