Introduction
A reverse proxy sees every request before your application does, which makes it the correct place to terminate TLS, cap request rates, and rewrite headers. When those directives are right, every service behind the proxy inherits the protection without changes to application code. When they are wrong, you find out through 502s, duplicate charges from retried POSTs, or a certificate that validates in Chrome and fails on an Android phone.
The config in this article targets nginx 1.24 on Debian 12 and nginx 1.26 on Ubuntu 24.04, with an upstream listening on loopback. It assumes you control DNS and can run certbot. Where a directive needs a newer nginx than a long-term-support distribution ships, the version section at the end explains the substitute. TLS 1.0 and 1.1 are treated as retired; if you still serve them, fix that before tuning anything else.
Where the stock config falls short
Most guides start with a block like this:
server { listen 80; server_name example.com; location / { proxy_pass http://127.0.0.1:8080; }}That forwards traffic and nothing more. It never tells the application the original scheme, so frameworks that force HTTPS build a redirect to http:// and loop. It does not set Host, so multi-tenant apps resolve the wrong tenant or generate absolute URLs with the upstream socket address. It has no timeouts, so a backend that stops responding holds worker connections until the client disconnects. The default body limit is 1 MB and the rejection is a bare 413 with no JSON body. The Server header advertises the exact nginx version. And there is no per-client limit, so one script with 200 concurrent sockets can starve everyone else.
Each of those gaps maps to a directive. The sections below add them in layers, and the complete config near the end puts the layers together.
Terminating TLS with a chain that validates
Certificates and renewal
Use certbot in webroot mode so the certificate tooling never rewrites your nginx files. The nginx plugin edits server blocks in place, which is convenient until it guesses wrong and you have to reconstruct a working config from a backup.
certbot certonly -a webroot -w /var/www/certbot -d example.com -d www.example.comThe files land under /etc/letsencrypt/live/example.com/. Point nginx at the full chain, not the leaf:
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;fullchain.pem is the leaf certificate followed by the intermediate. Serving only the leaf works in browsers that cache intermediates from previous visits or fetch them through the AIA extension, and fails on clients that do neither. Android is the usual canary. Run this and count the certificates:
echo | openssl s_client -showcerts -connect example.com:443 -servername example.com 2>/dev/null | grep -c "BEGIN CERTIFICATE"A result of 1 means the chain is incomplete. You want 2 or more, depending on the CA.
Renewal runs from a systemd timer installed by the certbot package. Reload nginx through a deploy hook script rather than a command flag, so manual renewals trigger it too:
cat >/etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'EOF'#!/bin/shsystemctl reload nginxEOFchmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.shThe hook runs only after a successful renewal, which is what you want. A reload on every timer tick is harmless but pointless.
Check expiry without logging into the box:
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -datesProtocols and ciphers
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:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;ssl_prefer_server_ciphers off;ssl_ecdh_curve X25519:prime256v1:secp384r1;The cipher list is the Mozilla intermediate profile and only affects TLS 1.2. TLS 1.3 suites are negotiated from the library defaults and ssl_ciphers does not touch them; on OpenSSL 1.1.1 and later you can adjust them with ssl_conf_command Ciphersuites, which is rarely necessary because the defaults are fine.
ssl_prefer_server_ciphers off lets the client choose from the list. Some compliance scanners flag this setting as a finding, usually because an old checklist assumed TLS 1.2 only. The Mozilla profile also sets it off. If a scanner forces the issue, turning it on removes client-side hardware acceleration preferences and does not make the connection more secure, so push back before changing it.
ssl_ecdh_curve with X25519 first requires a library that knows the curve. OpenSSL 1.1.1 and 3.x do. A build against an old LibreSSL may fail at startup with invalid curve, in which case drop to prime256v1.
DH parameters are only needed if you keep DHE ciphers in the list. Generating a 2048-bit file takes a few minutes of CPU:
openssl dhparam -out /etc/nginx/dhparam.pem 2048Then add ssl_dhparam /etc/nginx/dhparam.pem;. With an ECDHE-only list, skip the file and the CPU cost.
Sessions and OCSP
ssl_session_cache shared:SSL:10m;ssl_session_timeout 1d;ssl_session_tickets off;The shared cache is per worker set. The nginx documentation puts a megabyte at roughly 4,000 sessions, so 10 MB covers about 40,000, which is enough for a single node handling a few thousand concurrent clients. Session tickets are disabled because a stolen ticket key compromises forward secrecy for every session encrypted with it, and rotating keys across a fleet is work most teams do not do. If you run several nodes behind a load balancer, the shared cache does not cross hosts; sticky sessions are the simpler answer, or tickets with a rotation job.
OCSP stapling:
ssl_stapling on;ssl_stapling_verify on;resolver 1.1.1.1 8.8.8.8 valid=300s;resolver_timeout 5s;nginx fetches the OCSP response at runtime, which is why the resolver is required when the responder is named by hostname. Verification needs the issuer certificate, so ssl_trusted_certificate must point at the chain file. Let’s Encrypt wound down its OCSP responders in 2025 in favor of CRLs, so for those certificates the directives are harmless and do nothing. They still matter if your CA runs OCSP. Check with:
echo | openssl s_client -connect example.com:443 -servername example.com -status 2>/dev/null | grep -A2 "OCSP Response Status"HSTS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;Start with max-age=300 for a week, confirm that every subdomain speaks HTTPS, then raise it. includeSubDomains will break an internal host that only listens on port 80, and browsers will refuse to let users click through the warning. Adding preload commits every current and future subdomain to HTTPS for as long as the entry stays in the browser binaries, which is months after you remove the header. Do not add it because a scanner gave you a better grade.
The always parameter matters more than it looks. Without it, nginx omits the header on 4xx and 5xx responses generated by nginx itself, so the first request after an error can downgrade to HTTP.
Port 80, ACME, and unknown hosts
server { listen 80; listen [::]:80; server_name example.com www.example.com;
location /.well-known/acme-challenge/ { root /var/www/certbot; default_type "text/plain"; try_files $uri =404; }
location / { return 301 https://$host$request_uri; }}$host uses the Host header and falls back to the server name when the header is missing, so the redirect stays on the requested domain. $server_name collapses every host to the first name in the list, which breaks setups that serve several domains from one block. return 301 is cheaper than a rewrite with a regex and does not require a location match.
The ACME location must be evaluated before the redirect. certbot writes a token file under .well-known/acme-challenge/, and if the request is redirected to HTTPS the validation fails unless you duplicate the location in the TLS server. Serving the challenge only on port 80 is enough because the CA validates over HTTP.
Catch-all servers keep scanners away from the real certificate and avoid processing requests for hostnames you do not own:
server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 444;}
server { listen 443 ssl default_server; listen [::]:443 ssl default_server; ssl_reject_handshake on; server_name _;}return 444 closes the connection without sending a response, which costs less than a 404 page. ssl_reject_handshake (nginx 1.19.4 and later) refuses the TLS handshake for SNI names that match no server block, so a scanner connecting to the bare IP cannot read your certificate. On older nginx, give the default 443 server a self-signed certificate instead and accept that the name is visible.
Rate limiting that matches real traffic
The limit_req module implements a leaky bucket. Each key gets a bucket that drains at the configured rate; requests that arrive faster than the drain either queue or get rejected, depending on burst and nodelay.
limit_req_zone $binary_remote_addr zone=general:10m rate=20r/s;limit_req_zone $binary_remote_addr zone=auth:10m rate=5r/m;limit_conn_zone $binary_remote_addr zone=conn:10m;These go in the http block. The key is the client address in binary form: 4 bytes for IPv4 and 16 for IPv6, against roughly 7 to 15 bytes for the text form. The zone size determines how many states fit; the documentation puts a megabyte at about 16,000 states, so 10 MB holds roughly 160,000 clients. When the zone fills, nginx evicts the least recently used state, which means a client that has been quiet for a while gets a fresh bucket.
Rates use r/s or r/m. A rate of 20r/s allows one request every 50 ms on average. burst is the queue size above that rate. nodelay serves queued requests immediately instead of spacing them out, which is what an API wants: a client that fires 40 requests in one second should get 40 answers now, not one every 50 ms for two seconds while the page waits.
server { # ... limit_req zone=general burst=40 nodelay; limit_conn conn 20; limit_req_status 429; limit_conn_status 429; limit_req_log_level warn;}Changing the status to 429 matters. The default is 503, and some client libraries and CDNs treat 503 as a transient server failure and retry immediately, which multiplies the load that triggered the limit. 429 is understood as a request to back off. limit_conn caps simultaneous connections per address and catches slow readers that limit_req never sees, since a connection that sends one byte per second still consumes a worker.
Inheritance is the usual trap. A limit_req in a location replaces the one inherited from the server; it does not add to it. A stricter login limit looks like this:
location = /login { limit_req zone=auth burst=5 nodelay; proxy_pass http://backend;}Inside that location the general zone no longer applies. That is usually fine because the auth zone is stricter, but if you want both checks, put two directives on the same level:
limit_req zone=general burst=40 nodelay;limit_req zone=auth burst=5 nodelay;Both are evaluated and the first rejection wins.
Test a policy before enforcing it with limit_req_dry_run on; (nginx 1.17.1 and later). Excess requests are logged and served normally, so you can count what would have been rejected and tune the rate against real traffic.
Real client addresses behind a CDN
When traffic arrives through Cloudflare, Fastly, or an ALB, $binary_remote_addr is the edge address, not the visitor. Every user shares one bucket, and your first day of enforcement produces a wall of 429s.
set_real_ip_from 173.245.48.0/20;set_real_ip_from 103.21.244.0/22;# remaining published rangesreal_ip_header CF-Connecting-IP;real_ip_recursive on;Never use set_real_ip_from 0.0.0.0/0. Any client can send the header and choose its own rate limit key, which turns the limit into a suggestion. The real IP module walks the chain from the right when real_ip_recursive is on and stops at the first address that is not trusted, so listing only the CDN ranges is safe.
Confirm the result with a log format that prints both values:
log_format main '$remote_addr $http_cf_connecting_ip [$time_local] "$request" ' '$status $body_bytes_sent rt=$request_time urt=$upstream_response_time';access_log /var/log/nginx/access.log main;After the module runs, $remote_addr is the client and $http_cf_connecting_ip is the header the CDN sent. If they match, the configuration works. If $remote_addr still shows an edge address, the trusted range is wrong or the header name is not the one your CDN uses; Fastly sends Fastly-Client-IP, and AWS ALB sends X-Forwarded-For with the client on the right.
Header hardening in both directions
Response headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;add_header X-Content-Type-Options "nosniff" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'" always;X-Content-Type-Options: nosniff stops browsers from guessing a content type and executing an uploaded file as a script. Referrer-Policy controls how much of the URL leaks to third parties; strict-origin-when-cross-origin sends the full path for same-origin requests and only the origin for cross-origin ones.
CSP needs care. A policy with 'unsafe-inline' in script-src provides little protection, and many front-end frameworks inject inline scripts at boot. Start in report-only mode and collect violations for a week:
add_header Content-Security-Policy-Report-Only "default-src 'self'; report-uri /csp-report" always;The report-uri directive is deprecated in favor of report-to, but browser support for the newer endpoint format still varies, so production configs often send both. Enforce only after the reports are quiet.
X-Frame-Options: DENY and CSP frame-ancestors 'none' do the same job. frame-ancestors is the modern control and takes precedence in browsers that support it, so keep both during the transition if an audit requires the older header.
The inheritance rule for add_header causes more broken deployments than any other nginx behavior. Directives are inherited from the previous level only if there are no add_header directives at the current level. One add_header inside a location silently drops every header from the server block, including HSTS. The fix is an include file:
add_header X-Content-Type-Options "nosniff" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;Then include snippets/security-headers.conf; in every block that defines its own headers. Repeating the include is boring and correct.
Hiding what the backend leaks
proxy_hide_header X-Powered-By;proxy_hide_header X-AspNet-Version;proxy_hide_header X-AspNetMvc-Version;proxy_hide_header Server;server_tokens off;server_tokens off removes the version from nginx’s own Server header and from error pages, leaving Server: nginx. Removing the product name entirely requires the headers-more module and more_clear_headers Server;, which means an extra dynamic module package to track across upgrades. The gain is one less fingerprinting signal; most teams stop at server_tokens off.
proxy_hide_header only removes headers sent by the upstream. It cannot remove the Server header that nginx itself adds, which is why the two directives are usually paired.
Request headers to the upstream
proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $remote_addr;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-Host $host;proxy_set_header X-Forwarded-Port $server_port;proxy_set_header Connection "";Applications need X-Forwarded-Proto to build correct redirects and set secure cookie flags. Without it, a Django or Rails app behind TLS redirects to http:// and loops. Host $host preserves the requested hostname for multi-tenant routing and signed cookies.
The choice between $proxy_add_x_forwarded_for and $remote_addr is a security decision. $proxy_add_x_forwarded_for appends the client address to whatever the client sent, and if the backend trusts the leftmost entry, an attacker can forge it. With a single proxy and real IP already configured, X-Forwarded-For $remote_addr discards the client-supplied chain and passes the address nginx actually observed. If you need the full chain, make the backend read from the right and trust only your proxy addresses.
Connection "" clears the header for upstream keepalive. Without it, clients that send Connection: close cause the upstream socket to close after each request, and keepalive never helps.
Request header hygiene
underscores_in_headers off and ignore_invalid_headers on are defaults; leave them. Headers with underscores are dropped because some CGI stacks translate them into environment variables, which is a known injection path. large_client_header_buffers 4 16k; raises the limit for long cookies and JWTs. The default of four 8k buffers rejects oversized Authorization headers with a 400, and the error log shows client sent too long header line.
Timeouts, body limits, and buffers
client_max_body_size 8m;client_body_buffer_size 128k;client_header_timeout 10s;client_body_timeout 15s;send_timeout 15s;keepalive_timeout 30s;
proxy_connect_timeout 5s;proxy_send_timeout 30s;proxy_read_timeout 30s;proxy_buffer_size 16k;proxy_buffers 8 16k;proxy_busy_buffers_size 32k;The client timeouts are between successive read operations, not total request duration, so they limit slowloris without cutting off a large upload that is making progress. client_max_body_size should be set per location rather than globally; a global 100m lets any client fill client_body_temp_path and the disk behind it.
proxy_read_timeout 30s produces a 504 for any backend that takes longer, which is correct for most API calls and wrong for report generation. Raise it in the specific location, or move long work to a queue and return a job ID. Setting it to 600s globally means a stuck upstream holds worker connections for ten minutes during an incident.
proxy_buffer_size holds the response headers. Large cookies, JWTs, or a stack of redirect headers can exceed the default 4k or 8k and produce upstream sent too big header while reading response header from upstream. Raising it to 16k fixes the symptom. If one response carries a 12k cookie, fix the application too, because every response now pays that cost per connection.
Buffering trades memory for backend occupancy. With proxy_buffering on (the default), nginx reads the full response from the backend quickly and feeds slow clients from memory or disk, freeing the upstream connection. With buffering off, a slow client holds an upstream socket for the duration of the download. For large file downloads, off is often the right choice; for JSON APIs, leave it on.
Upstream keepalive
upstream backend { server 127.0.0.1:8080; keepalive 32; keepalive_timeout 60s; keepalive_requests 1000;}The keepalive value is the number of idle connections each worker keeps, not a global cap. Four workers with keepalive 32 can hold up to 128 idle sockets to the backend. Too low and you reconnect during every burst; too high and you waste file descriptors on the backend. Start at 32 and count sockets with ss -tan state established '( dport = :8080 )' | wc -l.
The upstream block alone does nothing without proxy_http_version 1.1 and proxy_set_header Connection "", because nginx defaults to HTTP/1.0 toward the backend and HTTP/1.0 has no persistent connections.
Set keepalive_timeout shorter than the backend’s idle timeout. If nginx reuses a socket the backend has already closed, the client gets a 502, and proxy_next_upstream retries on a fresh connection, hiding the race at the cost of latency. A backend idle timeout of 65 seconds and an nginx upstream keepalive of 60 seconds is the right ordering.
proxy_next_upstream defaults to error timeout, which means nginx may retry a request that already reached the backend. For POST endpoints that are not idempotent, cap retries with proxy_next_upstream_tries 2; or disable retries on those routes entirely. Duplicate charges are a worse outcome than a visible 502.
A complete configuration
# /etc/nginx/nginx.conf (excerpt)http { server_tokens off;
limit_req_zone $binary_remote_addr zone=general:10m rate=20r/s; limit_req_zone $binary_remote_addr zone=auth:10m rate=5r/m; limit_conn_zone $binary_remote_addr zone=conn:10m;
log_format main '$remote_addr [$time_local] "$request" $status ' '$body_bytes_sent rt=$request_time urt=$upstream_response_time'; access_log /var/log/nginx/access.log main;
upstream backend { server 127.0.0.1:8080; keepalive 32; keepalive_timeout 60s; }
server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 444; }
server { listen 80; listen [::]:80; server_name example.com www.example.com;
location /.well-known/acme-challenge/ { root /var/www/certbot; default_type "text/plain"; try_files $uri =404; }
location / { return 301 https://$host$request_uri; } }
server { listen 443 ssl default_server; listen [::]:443 ssl default_server; ssl_reject_handshake on; server_name _; }
server { listen 443 ssl; listen [::]:443 ssl; http2 on; # nginx 1.25.1+; on older builds use "listen 443 ssl http2;" server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.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:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384; ssl_prefer_server_ciphers off; ssl_ecdh_curve X25519:prime256v1:secp384r1;
ssl_session_cache shared:SSL:10m; 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;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'" always;
client_max_body_size 8m; client_body_buffer_size 128k; client_header_timeout 10s; client_body_timeout 15s; send_timeout 15s; keepalive_timeout 30s; large_client_header_buffers 4 16k;
limit_req zone=general burst=40 nodelay; limit_conn conn 20; limit_req_status 429; limit_conn_status 429; limit_req_log_level warn;
location = /login { limit_req zone=auth burst=5 nodelay; proxy_pass http://backend; include snippets/proxy-common.conf; }
location / { proxy_pass http://backend; include snippets/proxy-common.conf; }
error_page 429 /429.json; location = /429.json { internal; default_type application/json; return 429 '{"error":"rate_limited"}'; } }}proxy_http_version 1.1;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $remote_addr;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-Host $host;proxy_set_header X-Forwarded-Port $server_port;proxy_set_header Connection "";
proxy_connect_timeout 5s;proxy_send_timeout 30s;proxy_read_timeout 30s;
proxy_buffer_size 16k;proxy_buffers 8 16k;proxy_busy_buffers_size 32k;
proxy_hide_header X-Powered-By;proxy_hide_header Server;The 429 handler returns JSON for every route, including HTML pages. That is a deliberate simplification for an API-first deployment; a site that serves both should branch on $http_accept or use error_page 429 /429.html; for the HTML side.
Testing the result
Validate the syntax before every reload, and dump the merged config when you need to know which directive won:
nginx -tnginx -T | grep -nE "ssl_protocols|add_header|limit_req|proxy_set_header"Check the response headers:
curl -sI https://example.com | grep -iE 'strict-transport|content-security|x-content-type|referrer|server'The Server line should read nginx with no version, HSTS should be present, and CSP should match the policy you intended. Run the same command against a 404 path, because that is where missing always parameters show up.
Check protocol support. TLS 1.2 should complete, and TLS 1.1 should fail:
openssl s_client -connect example.com:443 -servername example.com -tls1_2 </dev/null 2>&1 | grep "Protocol"openssl s_client -connect example.com:443 -servername example.com -tls1_1 </dev/null 2>&1 | grep -iE "alert|no protocols"Modern OpenSSL 3 builds may refuse to offer TLS 1.1 at all unless legacy support is compiled in, which makes the second command inconclusive. testssl.sh -p -S -h example.com gives a full matrix and checks the headers at the same time.
Exercise the rate limit from a single address:
for i in $(seq 1 60); do curl -s -o /dev/null -w "%{http_code}\n" https://example.com/apidone | sort | uniq -cWith rate=20r/s and burst=40, expect roughly 40 immediate 200s and the rest mixed with 429s as the bucket drains. Watch the log while the loop runs:
tail -f /var/log/nginx/error.log | grep -i limitingA line like this is the expected output, not a bug:
2026/11/18 10:14:02 [warn] 812#812: *4021 limiting requests, excess: 19.000 by zone "general", client: 203.0.113.24, server: example.com, request: "GET /api HTTP/1.1", host: "example.com"Troubleshooting
nginx: [emerg] unknown directive “http2”
Full message: nginx: [emerg] unknown directive "http2" in /etc/nginx/conf.d/example.conf:42.
The http2 on; directive was added in nginx 1.25.1. Ubuntu 24.04 ships 1.24, so the config fails there. Run nginx -v before pasting. The fix is the older form:
listen 443 ssl http2;and remove the standalone http2 on; line. Both forms work on 1.25.1 and later, but the listen parameter is deprecated and will eventually be removed.
”ssl_stapling” ignored, issuer certificate not found
Full message: nginx: [warn] "ssl_stapling" ignored, issuer certificate not found for certificate "/etc/letsencrypt/live/example.com/fullchain.pem".
The certificate file has no intermediate, or ssl_trusted_certificate is missing or points at the wrong file. Use fullchain.pem for ssl_certificate and chain.pem for ssl_trusted_certificate, then reload. Verify with openssl s_client -status and look for OCSP Response Status: successful.
upstream sent too big header while reading response header from upstream
Full message: upstream sent too big header while reading response header from upstream, client: 203.0.113.24, server: example.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8080/", host: "example.com".
Response headers exceed proxy_buffer_size. Large Set-Cookie values, JWTs stored as cookies, or a stack of Link headers for preloading cause it. Raise the buffers:
proxy_buffer_size 16k;proxy_buffers 8 16k;proxy_busy_buffers_size 32k;If a single cookie is 12k, the application is the real problem; headers that size cost memory on every connection and some clients truncate them.
limiting requests on every request at low traffic
The log shows excess: 0.000 by zone "general" for ordinary users, and they see 429s. $binary_remote_addr is the CDN or load balancer address, so every visitor shares one bucket. Configure set_real_ip_from and real_ip_header, then confirm with the access log that $remote_addr is the client address before touching the rate.
The other common cause is an SPA that fetches 30 resources on load. A 40-request burst covers that, but only if all the requests hit the same zone. A stricter zone on a location replaces the general one, so a page load that crosses into /login loses the larger burst.
connect() failed (111: Connection refused)
Full message: connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.24, server: example.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8080/", host: "example.com".
The backend is not listening on that port. Check with ss -ltnp | grep 8080 on the backend host. If nginx runs in a container, 127.0.0.1 points at the nginx container, not the host; use the service name on a shared Docker network or the host gateway address. Running curl -v http://127.0.0.1:8080 from inside the nginx container separates a network problem from an application crash.
upstream timed out (110: Connection timed out)
Full message: upstream timed out (110: Connection timed out) while reading response header from upstream.
proxy_read_timeout is shorter than the backend’s response time, or the backend is blocked on a database lock. Raise the timeout in that location only. A global 600s hides the problem and lets a stuck upstream consume workers for ten minutes. Long-running work belongs in a queue with a polling endpoint.
413 Request Entity Too Large
The default client_max_body_size is 1m. Override it in the upload location, not globally:
location = /upload { client_max_body_size 100m; proxy_pass http://backend;}A global 100m invites disk exhaustion through client_body_temp_path, since every request can buffer to disk before the backend reads it. Pair large uploads with client_body_timeout and a rate limit on the endpoint.
worker_connections are not enough
Full message: worker_connections are not enough while connecting to upstream.
The events block limit is exhausted. The compiled default is 512, Debian and Ubuntu configs often set 768, and busy hosts need 4096 or more. Each proxied request uses a client connection and an upstream connection, so the effective ceiling is roughly half the worker connection count. Enable upstream keepalive as well, since HTTP/1.0 without it opens a new socket per request.
HSTS header missing on one route
add_header in that location replaced the inherited set. Add include snippets/security-headers.conf; to the location, or move all headers to the server level. Confirm with curl -sI https://example.com/that/route | grep -i strict and test an error path too, because always changes which responses carry the header.
no live upstreams while connecting to upstream
Every server in the upstream block is marked failed. The default is max_fails=1 and fail_timeout=10s, so a single connection error takes a backend out for ten seconds. With one backend, that means a brief outage after any restart. If the backend restarts often, raise max_fails or add a health check through proxy_next_upstream, and make sure the restart is graceful enough that nginx does not see a refused connection.
Version differences that break copy-paste configs
The distribution matters more than the version number. Ubuntu 20.04 ships nginx 1.18, Debian 12 ships 1.22, Ubuntu 24.04 ships 1.24, and the nginx.org repositories provide the 1.26 and 1.28 stable branches. Directives have arrival dates:
http2 onarrived in 1.25.1.ssl_reject_handshakearrived in 1.19.4.limit_req_dry_runarrived in 1.17.1.ssl_early_dataarrived in 1.15.3.- The
alwaysparameter onadd_headerarrived in 1.7.5.
TLS 1.3 needs OpenSSL 1.1.1 or newer at build time. Ubuntu 20.04 has 1.1.1 and Debian 12 has 3.0, so both work, but an nginx built against LibreSSL may not offer TLS 1.3 at all.
Module availability is the other trap. A slim container image may omit http_realip_module, and set_real_ip_from then fails with unknown directive. Check with nginx -V and look for -with-http_realip_module, -with-http_v2_module, and -with-http_stub_status_module. The official nginx images include the standard set; third-party minimal images sometimes do not.
HTTP/3 is available from 1.25.0 with a QUIC-capable TLS library:
listen 443 quic reuseport;add_header Alt-Svc 'h3=":443"; ma=86400';It adds a UDP path that some corporate firewalls drop silently, so keep HTTP/2 on the same server block and let clients fall back.
A scenario worth walking through
Consider an API behind Cloudflare with a global limit of 10r/s and a burst of 20. After enabling enforcement, the support queue fills with reports that the dashboard never loads, and the error log shows 429s from a handful of addresses in the 172.70.0.0/16 range. The addresses are Cloudflare edges, not customers.
The first fix is the real IP configuration. set_real_ip_from gets the published ranges, real_ip_header CF-Connecting-IP names the header, and real_ip_recursive on handles the chain. After a reload, the access log shows customer addresses in $remote_addr, and the 429s spread across many keys instead of concentrating on a few.
The second fix is the rate itself. A dashboard load fetches a session, a user profile, a list of projects, and a dozen widget endpoints. Twenty requests in the first second is normal, so a burst of 20 rejects the page half the time. Raising the burst to 60 and the rate to 20r/s covers the load while still stopping a script that fires hundreds of requests. The login endpoint keeps its own zone at 5r/m with a burst of 5, because credential stuffing looks nothing like a dashboard.
The lesson is that rate limits are only as good as the key they use. A correct key with a rate that ignores how the application loads is still a broken deployment.
What to watch after deployment
Certificate expiry is the failure that takes the whole site down, so monitor it from outside rather than trusting the renewal timer. A check every hour that parses notAfter from openssl s_client and alerts at 14 days catches a broken renewal hook before users do.
Watch the 429 ratio as a first-class metric. A sudden rise means either an attack or a legitimate client pattern you did not account for. Both need a look; only one needs a firewall rule.
Keep the nginx config in version control and run nginx -T in CI against a staging container. The merged output shows which add_header won and whether an include is missing. After every nginx upgrade, re-run the header and protocol checks, because defaults change between minor versions and a config that passed last quarter can fail silently.
Finally, read the error log after each change. The directives in this article produce clear warnings when they are misconfigured, and those warnings appear at reload time, not at 3 a.m. when the certificate expires.
Conclusion
A reverse proxy is a small piece of software with a large blast radius. The config above covers the parts that break most often: an incomplete certificate chain, TLS versions that should be off, a rate limit keyed on the wrong address, headers that disappear on error responses, and timeouts that hold workers hostage.
Put the files in git, run nginx -t before every reload, and verify the result from outside with curl and openssl s_client rather than trusting the config to mean what you think it means. The next upgrade will change a default somewhere; the tests are how you find out before your users do.