Reverse proxies fail security audits in predictable ways. Usually it is not because someone forgot TLS—it is because a single add_header Cache-Control inside a static asset location block silently wiped every server-level security header, or an .env / .git file remained readable behind a catch-all proxy rule.

This guide walks through production-ready Nginx and Caddy reverse proxy hardening in 2026—including TLS 1.2/1.3 configuration, HSTS preload rollout, strict CSP and COOP/CORP isolation, dotfile blocking, per-IP rate limiting, and a zero-dependency Python 3 header auditor.

1. The #1 Nginx Security Footgun: add_header Inheritance Drop

In Nginx, add_header directives are inherited from http -> server -> location only if the child block defines zero add_header directives of its own.

The moment you add a single add_header Cache-Control "public, max-age=31536000, immutable"; inside location /assets/, Nginx drops every Content-Security-Policy, Strict-Transport-Security, and X-Content-Type-Options header defined at the server level for that location.

Also, without the always parameter, Nginx omits add_header on 4xx and 5xx error responses (such as 401, 404, or 429).

Fix: Extract a Shared Snippet + Use always

Put your security headers in /etc/nginx/snippets/security-headers.conf and include it in server {} and inside any location {} block that declares its own add_header:

# /etc/nginx/snippets/security-headers.conf 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 Cross-Origin-Opener-Policy "same-origin" always; add_header Cross-Origin-Resource-Policy "same-origin" always; add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always; add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests" always; 

Then include it explicitly whenever a child location needs custom caching:

server { include /etc/nginx/snippets/security-headers.conf; location /assets/ { include /etc/nginx/snippets/security-headers.conf; add_header Cache-Control "public, max-age=31536000, immutable" always; try_files $uri =404; } } 

2. TLS 1.2 & TLS 1.3 Hardening (2026 Baseline)

Disable legacy TLS 1.0/1.1, disable session tickets (ssl_session_tickets off; preserves forward secrecy across restarts), and let modern TLS 1.3 / AEAD clients choose their fastest cipher (ChaCha20 on mobile, AES-GCM on AES-NI servers):

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; ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d; ssl_session_tickets off; server_tokens off; 

2026 note on OCSP Stapling: Major CAs including Let's Encrypt retired OCSP responders in favor of CRLs and shorter-lived certificates. If you use Let's Encrypt, remove ssl_stapling on; to avoid noisy Nginx startup warnings (OCSP_basic_verify / missing OCSP responder URLs).

Safe HSTS Preload Rollout Steps

Do not ship preload on day one—removing a domain from browser preload lists takes months and breaks any plain-HTTP subdomain:

  1. Stage 1 (Verify HTTPS everywhere): max-age=300 (5 minutes) — test all routes and subdomains.
  2. Stage 2 (Ramp up): max-age=86400; includeSubDomains (24 hours) — confirm internal tools, staging, and mail autodiscover subdomains have valid TLS.
  3. Stage 3 (1-year + Preload): max-age=31536000; includeSubDomains; preload — only once every subdomain under the apex serves valid HTTPS.

3. Blocking Dotfiles (.env, .git) Without Breaking ACME

Never block all dot-paths blindly with location ~ /\., or you will break /.well-known/acme-challenge/ renewals and /.well-known/security.txt. Use a negative lookahead to exempt .well-known and return 404 (avoiding 403 existence leaks):

location ~ /\.(?!well-known).* { deny all; access_log off; log_not_found off; return 404; } 

4. Per-IP Rate-Limit Zones (auth vs api)

Define separate limit_req_zone buckets in http {} so strict login throttling does not starve normal API calls:

# http {} context limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=5r/m; limit_req_zone $binary_remote_addr zone=api_limit:20m rate=30r/s; limit_req_status 429; 

Apply them per route inside server {}:

location ~ ^/(login|auth|token|password-reset) { limit_req zone=auth_limit burst=5 nodelay; proxy_pass http://app_upstream; } location /api/ { limit_req zone=api_limit burst=40 nodelay; proxy_pass http://app_upstream; } 

If Nginx sits behind Cloudflare or an ALB, restore the real client IP with set_real_ip_from + real_ip_header first—otherwise $binary_remote_addr rate-limits your load balancer IP and locks out every user at once.

5. Equivalent Hardened Caddyfile ((security_headers) Snippet)

Caddy v2 enables TLS 1.2/1.3, automatic ACME renewals, and HTTPS redirects out of the box, and does not suffer from Nginx's add_header inheritance drop—yet you still need explicit security headers, dotfile blocks, and server header stripping (-Server):

(security_headers) { header { Strict-Transport-Security "max-age=31536000; includeSubDomains" X-Content-Type-Options "nosniff" Referrer-Policy "strict-origin-when-cross-origin" Cross-Origin-Opener-Policy "same-origin" Cross-Origin-Resource-Policy "same-origin" Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests" -Server } } app.example.com { import security_headers @dotfiles path_regexp dotfiles ^/\.(?!well-known) handle @dotfiles { respond 404 } handle /assets/* { header Cache-Control "public, max-age=31536000, immutable" root * /srv/www file_server } handle { reverse_proxy 127.0.0.1:8080 } } 

6. Security Header Matrix (What to Check in CI)

Header Target Value Why It Matters
Strict-Transport-Security max-age=31536000; includeSubDomains Prevents SSL stripping & downgrade attacks
Content-Security-Policy default-src 'self'; frame-ancestors 'none'; object-src 'none' Mitigates XSS, data exfiltration, and clickjacking
Cross-Origin-Opener-Policy same-origin Isolates browsing context group from cross-origin popups
Cross-Origin-Resource-Policy same-origin (or same-site) Blocks cross-origin <script>/<img> side-channel reads
X-Content-Type-Options nosniff Disables MIME-type sniffing on uploads/static files
Referrer-Policy strict-origin-when-cross-origin Prevents leaking full URLs/tokens in Referer
Permissions-Policy camera=(), microphone=(), geolocation=() Locks down unused browser sensor APIs

7. Zero-Dependency Python 3 Header & Exposure Auditor

Run this standard-library script against staging or production after every proxy config change (and against /assets/ specifically to catch Nginx add_header inheritance drops):

#!/usr/bin/env python3 import ssl, sys, urllib.error, urllib.request REQUIRED = { "strict-transport-security": "max-age=", "content-security-policy": "default-src", "cross-origin-opener-policy": "same-origin", "cross-origin-resource-policy": "same-", "x-content-type-options": "nosniff", "referrer-policy": "strict-origin", "permissions-policy": "camera=()", } def fetch(url): req = urllib.request.Request(url, method="GET") try: with urllib.request.urlopen(req, timeout=8, context=ssl.create_default_context()) as r: return r.status, {k.lower(): v for k, v in r.headers.items()} except urllib.error.HTTPError as e: return e.code, {k.lower(): v for k, v in e.headers.items()} base = sys.argv[1].rstrip("/") failed = False for path in ["/", "/nonexistent-404-check"]: status, headers = fetch(base + path) print(f"\n[{status}] {base + path}") for h, needle in REQUIRED.items(): val = headers.get(h, "") ok = needle in val.lower() print(f" {\"PASS\" if ok else \"FAIL\"} {h}: {val or \"<missing>\"}") if not ok: failed = True for secret in ["/.env", "/.git/HEAD"]: status, _ = fetch(base + secret) ok = status in (403, 404) print(f" {\"PASS\" if ok else \"FAIL\"} {secret} -> HTTP {status}") if not ok: failed = True sys.exit(1 if failed else 0) 

Testing both / and /nonexistent-404-check immediately catches missing always flags on Nginx add_header directives, while the /.env and /.git/HEAD probes catch misordered regex blocks before scanners do.