- Introduction to Reverse Proxies
- What is Nginx?
- What is Caddy?
- How Reverse Proxy Architecture Works
- Nginx vs Caddy Architecture Comparison
- Detailed Feature Comparison
- Installation on Ubuntu 24.04
- Nginx — Practical Configuration Examples
- Caddy — Practical Configuration Examples
- Docker Compose Deployment
- Production-Level Considerations
- Performance Discussion
- Final Verdict
- FAQ
- Conclusion & References
Every modern web application sits behind a reverse proxy. Whether you're routing traffic to microservices, terminating TLS, load-balancing across backend pods, or enforcing rate limits — the reverse proxy is the front door of your infrastructure. Two servers have emerged as the dominant choices for this role: Nginx, the battle-tested veteran powering roughly 34% of the top million websites (W3Techs, 2024), and Caddy, the Go-native challenger that made automatic HTTPS mainstream.
This guide cuts through the marketing noise with a production-calibre, side-by-side comparison. You will walk away with working configuration files, Docker Compose deployments, and a clear decision framework for your next infrastructure project.
Who is this for? DevOps Engineers, Cloud Architects, System Administrators, and Developers who already know what a web server is and want a deep, technically accurate comparison — not a beginner "which one should I use?" overview.
1. Introduction to Reverse Proxies
A reverse proxy is a server that sits in front of one or more backend application servers and forwards client requests to them. From the client's perspective, it is communicating directly with the reverse proxy — the backend servers are never exposed.
This architecture provides several critical capabilities:
- TLS termination: The proxy handles the computationally expensive TLS handshake so your application can speak plain HTTP internally.
- Load balancing: Traffic is distributed across multiple backend instances, enabling horizontal scaling.
- Request routing: Different URL paths or hostnames are routed to different upstream services (service mesh / API gateway patterns).
- Caching: Responses can be cached at the proxy layer to offload backend compute.
- Security: DDoS mitigation, rate limiting, WAF integration, and hiding internal topology from the public internet.
- Observability: Centralised access logs, latency metrics, and error tracking at the network edge.
Internet / Client
│
│ HTTPS :443
▼
┌─────────────────────────────────┐
│ Reverse Proxy │
│ (Nginx / Caddy) │
│ │
│ • TLS Termination │
│ • Request Routing │
│ • Load Balancing │
│ • Rate Limiting │
│ • Security Headers │
│ • Access Logging │
└───────────┬─────────────────────┘
│ HTTP (plain) — internal network
┌─────┴──────────────┐
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│ App :3000│ ... │ App :3001│
│ (Node.js)│ │ (Python) │
└──────────┘ └──────────┘
2. What is Nginx?
Nginx (pronounced "engine-x") was created by Igor Sysoev and first released publicly in 2004 to solve the C10K problem — the challenge of handling 10,000 concurrent connections on commodity hardware that plagued Apache's thread-per-connection model.
Nginx uses an event-driven, asynchronous, non-blocking I/O architecture. A small number of worker processes (typically equal to the number of CPU cores) each run a single-threaded event loop. This means a single Nginx worker can handle thousands of simultaneous connections without spawning a thread per connection.
┌─────────────────────────────────────────────────────┐ │ Nginx Process Model │ │ │ │ ┌────────────────┐ │ │ │ Master Process│ ← reads config, manages │ │ │ (single) │ worker lifecycle │ │ └───────┬────────┘ │ │ │ fork() │ │ ┌─────┴──────────────────┐ │ │ ▼ ▼ ▼ │ │ ┌──────┐ ┌──────┐ ┌──────┐ │ │ │Worker│ │Worker│ │Worker│ ← 1 per CPU core │ │ │(epoll│ │(epoll│ │(epoll│ each runs an │ │ │ loop)│ │ loop)│ │ loop)│ event loop │ │ └──────┘ └──────┘ └──────┘ │ │ │ │ Each worker handles thousands of connections │ │ simultaneously via non-blocking I/O │ └─────────────────────────────────────────────────────┘
Key characteristics of Nginx:
- Written in C — extremely low memory footprint, predictable latency.
- Static configuration files (
nginx.conf), reload required for changes. - Module-based architecture (static compilation or dynamic modules).
- Powers: Netflix, Cloudflare (historically), GitLab, WordPress.com, and many AWS-native setups.
- Commercial variant: Nginx Plus (F5) adds active health checks, JWT auth, dashboard, and dynamic upstreams.
- Current stable version: 1.26.x (as of late 2024); mainline 1.27.x.
3. What is Caddy?
Caddy was created by Matt Holt and first released in 2015 with one headline feature: automatic HTTPS by default. It was the first production-ready web server to provision Let's Encrypt certificates and handle renewals entirely automatically — with zero configuration.
Caddy is written in Go and uses goroutines for concurrency, which provides high throughput while keeping the codebase approachable for extensions. It exposes a live JSON API for configuration changes without reloads.
┌───────────────────────────────────────────────────────┐ │ Caddy Architecture │ │ │ │ ┌────────────────────────────────────────────────┐ │ │ │ Caddy Core (single binary, ~50 MB) │ │ │ │ │ │ │ │ Config Layer: Caddyfile → JSON API │ │ │ │ TLS Engine: certmagic (ACME client) │ │ │ │ HTTP Layer: http.Handler chain │ │ │ │ Plugin System: Go modules │ │ │ └────────────────────────────────────────────────┘ │ │ │ │ │ ┌──────────────┼──────────────┐ │ │ ▼ ▼ ▼ │ │ Let's Encrypt ZeroSSL Custom CA │ │ (ACME HTTP-01) (ACME) (internal) │ │ │ │ ┌────────────────────────────────────────────────┐ │ │ │ Admin API :2019 (live config, no reload) │ │ │ └────────────────────────────────────────────────┘ │ └───────────────────────────────────────────────────────┘
Key characteristics of Caddy:
- Written in Go — single self-contained binary, no dependencies.
- Automatic HTTPS via CertMagic (ACME protocol) — certificates provisioned and renewed automatically.
- Live JSON admin API at
localhost:2019for zero-downtime configuration changes. - Human-friendly Caddyfile syntax or full JSON API for programmatic control.
- Powers: smaller SaaS platforms, containerised microservice deployments, developer tools.
- Current stable version: 2.8.x (as of late 2024).
4. How Reverse Proxy Architecture Works
When a client makes a request, the reverse proxy performs several operations in sequence:
Client Browser
│
│ 1. DNS lookup → resolves to proxy IP
│ 2. TCP connection to :443
│ 3. TLS ClientHello
▼
Reverse Proxy
│ 4. TLS handshake (certificate presented)
│ 5. HTTP request received (decrypted)
│ 6. Host/path matching → select upstream
│ 7. Apply middleware (rate limit, auth, headers)
│ 8. Forward request to upstream (HTTP/1.1 or HTTP/2)
│ 9. Receive upstream response
│ 10. Optionally cache response
│ 11. Add response headers (HSTS, CSP, etc.)
│ 12. Write response back to client (re-encrypted)
│ 13. Write access log entry
▼
Client receives response
│
└── Connection kept alive (keep-alive / HTTP/2 mux)
Connection Pooling and Keep-Alive
A critical performance detail: the reverse proxy maintains a connection pool to upstream servers. Rather than opening a new TCP connection for every client request, it reuses existing connections. This dramatically reduces latency for high-traffic scenarios — establishing a TCP connection costs at minimum one round-trip, and a TLS connection costs two or three.
Health Checking
Production reverse proxies continuously probe upstream health. When a backend fails a health check, it is removed from the rotation. Nginx open-source uses passive health checks (removes a backend after a configurable number of consecutive failures on real traffic). Nginx Plus and Caddy both support active health checks (periodic synthetic probes independent of real traffic).
5. Nginx vs Caddy Architecture Comparison
NGINX CADDY ───────────────────────── ───────────────────────── Language: C Language: Go Model: Event-loop (epoll) Model: Goroutines Config: File (reload req.) Config: File or JSON API TLS: OpenSSL / BoringSSL TLS: x/crypto + certmagic HTTPS: Manual cert mgmt HTTPS: Fully automatic Modules: C modules (compile) Modules: Go plugins API: No live API (OSS) API: JSON REST at :2019 Reload: nginx -s reload Reload: API or caddy reload Config size: Verbose, explicit Config size: Terse, opinionated Docs: Comprehensive Docs: Good, growing
6. Detailed Feature Comparison
6.1 Performance
Both Nginx and Caddy are capable of handling very high concurrency with low resource usage. Meaningful architectural differences exist:
- Nginx (C + epoll/kqueue): Worker processes are extremely lean — a typical Nginx worker handling 10,000 idle connections consumes a few MB of RAM. The C implementation avoids garbage collection pauses entirely. This makes Nginx predictable under load spikes.
- Caddy (Go + goroutines): Go's runtime uses goroutines (lightweight green threads, ~2–8 KB stack each) managed by an M:N scheduler. This is highly concurrent, but Go's garbage collector introduces periodic STW (stop-the-world) pauses — typically sub-millisecond in modern Go versions, but measurable under extreme load.
Honest note on benchmarks: Published benchmarks are highly sensitive to test methodology, hardware, OS tuning, TLS cipher suite, connection type (keep-alive vs. new), and payload size. Independent benchmarks (such as those from TechEmpower) have shown Nginx and Caddy performing comparably for typical web workloads. Do not trust vendor-published numbers. Run your own benchmarks with
wrk,hey, orvegetaagainst your specific workload before making a decision on performance grounds.
# Install wrk (HTTP benchmarking tool) sudo apt install wrk -y # 30-second test: 500 concurrent connections, 4 threads wrk -t4 -c500 -d30s --latency https://your-domain.com/ # Install hey (simpler Go-based load tester) go install github.com/rakyll/hey@latest # 100,000 requests, 200 concurrent, report latency distribution hey -n 100000 -c 200 https://your-domain.com/ # Install vegeta for rate-controlled load testing go install github.com/tsenart/vegeta@latest # Constant 1000 req/s for 30 seconds, report percentiles echo "GET https://your-domain.com/" | \ vegeta attack -rate=1000 -duration=30s | \ vegeta report --type=text
6.2 Configuration
This is one of the starkest differences between the two.
Nginx uses an nginx.conf with an explicit, hierarchical block syntax. Configuration is expressive but verbose. Every directive is documented and there are rarely implicit defaults — you must state what you want. This verbosity becomes a strength in complex, heavily tuned production environments where every setting is explicit and auditable.
Caddy offers two configuration interfaces: the Caddyfile (a human-readable DSL with sensible defaults) and the JSON API (the native format, suitable for programmatic management). The Caddyfile makes common tasks — virtual hosts, proxying, HTTPS — trivially simple. The JSON API makes dynamic reconfiguration possible without touching files.
6.3 HTTPS / SSL / TLS
This is Caddy's most significant technical differentiator.
Feature │ Nginx (OSS) │ Caddy ─────────────────────────────┼──────────────────────────┼────────────────────────── Certificate provisioning │ Manual (certbot / scripts)│ Automatic (CertMagic) Certificate renewal │ Manual cron / certbot │ Automatic (background) TLS 1.3 support │ Yes (OpenSSL ≥ 1.1.1) │ Yes (Go x/crypto) HTTP-01 ACME challenge │ Via certbot webroot │ Built-in DNS-01 ACME challenge │ Via certbot plugins │ Built-in (60+ providers) TLS-ALPN-01 ACME challenge │ No │ Built-in OCSP stapling │ Manual directive │ Automatic HSTS preloading │ Manual header │ One-line option Wildcard certs │ Via certbot DNS-01 │ Built-in DNS-01 On-demand TLS │ Not available │ Available (dynamic cert) Internal CA (mTLS) │ Manual setup │ Built-in PKI module
On-demand TLS (Caddy-exclusive) is particularly powerful: Caddy can provision certificates for arbitrary hostnames on the first request, without pre-configuration. This is ideal for multi-tenant SaaS platforms where each customer brings their own domain.
6.4 Load Balancing
Algorithm │ Nginx (OSS) │ Nginx Plus │ Caddy ────────────────────────┼───────────────┼─────────────┼────────────── Round-robin │ ✅ │ ✅ │ ✅ Least connections │ ✅ │ ✅ │ ✅ IP hash (sticky) │ ✅ │ ✅ │ ✅ (cookie) Weighted │ ✅ │ ✅ │ ✅ Random │ ❌ │ ✅ │ ✅ First available │ ❌ │ ✅ │ ✅ Active health checks │ ❌ │ ✅ │ ✅ Passive health checks │ ✅ │ ✅ │ ✅ Dynamic upstream update │ ❌ │ ✅ │ ✅ (JSON API)
6.5 Security
Both servers support comprehensive security hardening. Key differences:
- Nginx has a mature, battle-tested security track record. The
modsecurityWAF module integrates viangx_http_modsecurity_module(dynamic). Security headers must be configured manually but every header is controllable. - Caddy ships with sane security defaults: TLS 1.2 minimum, modern cipher suites, OCSP stapling all out of the box. The
caddy-securityplugin adds OAuth2/OIDC, JWT, and form-based auth as first-class middleware.
6.6 Caching
Nginx includes a powerful proxy_cache module in the open-source version. It supports memory-based key storage, disk-based content storage, cache-control header respect, background revalidation (proxy_cache_background_update), and stale-while-revalidate semantics. This is production-grade HTTP caching available in the free version.
Caddy does not include a caching module in its standard build. The community cache-handler module (powered by Souin) provides RFC 7234-compliant HTTP caching, but requires installing Caddy from source with the module or using a pre-built custom binary via xcaddy.
6.7 Rate Limiting
Nginx provides the ngx_http_limit_req_module (leaky bucket algorithm) and ngx_http_limit_conn_module (concurrent connection limits) in the base OSS package. These are robust, well-understood, and widely documented.
Caddy offers rate limiting via the caddy-ratelimit community module. It supports token-bucket rate limiting with zone-based tracking. Installation requires a custom build.
6.8 Monitoring and Logging
Feature │ Nginx │ Caddy ─────────────────────────────┼──────────────────────────┼────────────────────────── Access log format │ Custom (log_format) │ JSON structured (default) Error logs │ File │ Stderr / file (JSON) Prometheus metrics │ nginx-prometheus-exporter│ /metrics endpoint (built-in) OpenTelemetry │ Via OTEL module (nginx+) │ caddy-opentelemetry module Request tracing │ Manual header injection │ caddy-opentelemetry module Admin API │ Nginx Plus only │ Built-in :2019
Caddy's structured JSON logging is a significant operational advantage. Log lines are machine-parseable out of the box, making integration with Loki, Elasticsearch, or CloudWatch Logs straightforward without custom log format configuration.
6.9 Scalability
Both servers scale horizontally trivially — place multiple instances behind an L4 load balancer (AWS NLB, GCP Network LB). Vertical scaling is different:
- Nginx scales vertically by adding more worker processes (
worker_processes auto;). Each worker is pinned to CPU cores viaworker_cpu_affinity auto;. It can handle hundreds of thousands of concurrent connections on a large instance. - Caddy scales vertically via Go's runtime scheduler distributing goroutines across all available CPU cores automatically. No manual tuning required. Memory usage grows with active goroutines but remains reasonable.
6.10 Community and Ecosystem
- Nginx: One of the largest communities in infrastructure software. Extensive Stack Overflow coverage, countless production references, deeply documented modules, and commercial support from F5. The plugin ecosystem is mature (lua scripting via
openresty, ModSecurity WAF, Brotli compression, etc.). - Caddy: Smaller but active and growing community. Official Discord, GitHub Discussions, and a growing plugin ecosystem via
xcaddy. The community module quality varies — vet modules before using in production.
Category │ Nginx (OSS 1.26) │ Caddy 2.8 ──────────────────────┼─────────────────────────┼───────────────────────── Language │ C │ Go Automatic HTTPS │ ❌ (manual certbot) │ ✅ (CertMagic / ACME) Certificate renewal │ ❌ (cron + certbot) │ ✅ (fully automatic) On-demand TLS │ ❌ │ ✅ Config syntax │ nginx.conf (C-like) │ Caddyfile / JSON API Live config API │ ❌ │ ✅ (:2019 JSON API) Config reload │ nginx -s reload │ caddy reload Built-in caching │ ✅ (proxy_cache) │ ⚠️ (community module) Built-in rate limit │ ✅ (limit_req) │ ⚠️ (community module) Built-in auth │ ❌ (basic auth only) │ ⚠️ (caddy-security plugin) Prometheus metrics │ ⚠️ (exporter sidecar) │ ✅ (native endpoint) Structured JSON logs │ ⚠️ (manual format) │ ✅ (default) Active health checks │ ❌ (Nginx Plus only) │ ✅ Websocket proxying │ ✅ │ ✅ gRPC proxying │ ✅ │ ✅ HTTP/2 upstream │ ✅ (1.25.1+) │ ✅ HTTP/3 / QUIC │ ✅ (1.25.0+ experimental)│ ✅ (stable) Memory footprint │ Very low (~2MB/worker) │ Low (~30-50MB total) Binary size │ N/A (system package) │ ~50 MB single binary Commercial support │ ✅ (F5 / Nginx Plus) │ ⚠️ (community only) Plugin ecosystem │ Mature (C modules) │ Growing (Go modules)
7. Installation on Ubuntu 24.04
7.1 Install Nginx
# Update package index sudo apt update # Install Nginx from Ubuntu's upstream-synced repo sudo apt install nginx -y # Verify installation nginx -v # nginx version: nginx/1.24.0 (Ubuntu) # Enable and start Nginx sudo systemctl enable nginx sudo systemctl start nginx # Verify status sudo systemctl status nginx # Check which ports Nginx is listening on sudo ss -tlnp | grep nginx # Test configuration syntax before making changes sudo nginx -t # --- Add Nginx's official repo for the latest stable (1.26.x) --- # Import signing key curl -fsSL https://nginx.org/keys/nginx_signing.key | \ sudo gpg --dearmor -o /usr/share/keyrings/nginx-archive-keyring.gpg # Add official stable repo echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \ http://nginx.org/packages/ubuntu noble nginx" | \ sudo tee /etc/apt/sources.list.d/nginx.list sudo apt update && sudo apt install nginx -y # Verify updated version nginx -v
7.2 Install Caddy
# Install required tools sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl # Import Caddy's GPG key curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | \ sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg # Add Caddy's official APT repository curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | \ sudo tee /etc/apt/sources.list.d/caddy-stable.list # Install Caddy sudo apt update && sudo apt install caddy -y # Verify installation caddy version # v2.8.4 # Caddy is automatically enabled as a systemd service sudo systemctl status caddy # Caddy's main config file location # /etc/caddy/Caddyfile # Test config syntax caddy validate --config /etc/caddy/Caddyfile # Apply config changes (zero-downtime reload) sudo caddy reload --config /etc/caddy/Caddyfile
8. Nginx — Practical Configuration Examples
8.1 Basic Reverse Proxy
Nginx configuration follows a hierarchical context model: http {} → server {} → location {}. The proxy_pass directive is the core reverse proxy instruction.
server {
listen 80;
server_name app.example.com;
# Redirect all HTTP to HTTPS
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
http2 on; # Requires Nginx 1.25.1+
server_name app.example.com;
# --- TLS configuration ---
ssl_certificate /etc/ssl/certs/app.example.com.crt;
ssl_certificate_key /etc/ssl/private/app.example.com.key;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# Modern TLS protocol versions only
ssl_protocols TLSv1.2 TLSv1.3;
# Modern cipher suite (prioritise TLS 1.3, AES-GCM for TLS 1.2)
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;
ssl_prefer_server_ciphers off; # Let client choose from approved list
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# --- Security headers ---
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header X-Frame-Options DENY always;
add_header X-Content-Type-Options nosniff always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
# --- Reverse proxy ---
location / {
proxy_pass http://backend; # Named upstream group (defined below)
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 Upgrade $http_upgrade; # WebSocket support
proxy_set_header Connection "upgrade"; # WebSocket support
# Timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# Buffering (tune for your app's response sizes)
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
# Health check endpoint (do not proxy; return 200 from Nginx directly)
location /healthz {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
# Static assets — serve directly from disk (bypass backend)
location /static/ {
root /var/www/app;
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
}
8.2 Upstream Backend Pool with Load Balancing
upstream backend {
# Load balancing algorithm
# Remove these comments for the algorithm you want:
# (default = round-robin)
least_conn; # Route to the server with fewest active connections
# ip_hash; # Sticky sessions based on client IP
# random two; # Pick 2 at random, then apply least_conn (Nginx Plus)
# Backend servers
server 10.0.1.10:3000 weight=3; # Gets 3x the traffic (more capable host)
server 10.0.1.11:3000 weight=1;
server 10.0.1.12:3000 weight=1;
# Passive health check: mark server down after 3 fails in 30 seconds
# (OSS only — active health check requires Nginx Plus)
server 10.0.1.10:3000 max_fails=3 fail_timeout=30s;
# Keep-alive connections to backend pool (reduces connection overhead)
keepalive 32; # 32 idle keep-alive connections per worker
}
# Rate limiting zone: 10 MB shared memory, 10 requests/sec per unique IP
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
listen 443 ssl;
# ... (TLS config as above) ...
location /api/ {
# Apply rate limit: burst of 20 requests, no delay for first 20
limit_req zone=api_limit burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection ""; # Required for keepalive to upstream
# ... (headers as above) ...
}
}
8.3 Multi-Service Routing (API Gateway Pattern)
upstream auth_service { server 10.0.1.20:4000; keepalive 16; }
upstream user_service { server 10.0.1.21:4001; keepalive 16; }
upstream product_service { server 10.0.1.22:4002; keepalive 16; }
upstream order_service { server 10.0.1.23:4003; keepalive 16; }
server {
listen 443 ssl;
http2 on;
server_name api.example.com;
# ... TLS and headers ...
# Route by URL path prefix to different microservices
location /auth/ {
proxy_pass http://auth_service/;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /users/ {
proxy_pass http://user_service/;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /products/ {
proxy_pass http://product_service/;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /orders/ {
proxy_pass http://order_service/;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
8.4 Caching Configuration
http {
# Define cache zone: keys in 10MB shared memory, up to 1GB cache on disk
proxy_cache_path /var/cache/nginx
levels=1:2
keys_zone=main_cache:10m
max_size=1g
inactive=60m
use_temp_path=off;
# ... upstream and server blocks ...
}
# In your server/location block:
location / {
proxy_pass http://backend;
proxy_cache main_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
# Cache successful responses for 1 minute
proxy_cache_valid 200 302 1m;
proxy_cache_valid 404 1m;
# Serve stale cache while refreshing in background (reduces latency spikes)
proxy_cache_background_update on;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
# Pass cache status to client for debugging
add_header X-Cache-Status $upstream_cache_status;
}
9. Caddy — Practical Configuration Examples
9.1 Basic Reverse Proxy with Automatic HTTPS
The following Caddyfile is functionally equivalent to the Nginx configuration above — including TLS termination with automatic certificate provisioning from Let's Encrypt, security headers, and proxy forwarding. The difference in verbosity is striking.
app.example.com {
# Caddy automatically:
# - Obtains a TLS certificate from Let's Encrypt via HTTP-01 challenge
# - Renews it before expiry (checks every 10 minutes)
# - Enables OCSP stapling
# - Redirects HTTP → HTTPS
# Reverse proxy to backend
reverse_proxy localhost:3000 {
# Pass real client IP
header_up X-Real-IP {remote_host}
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto {scheme}
# Health check: active probing (not available in Nginx OSS)
health_uri /healthz
health_interval 10s
health_timeout 5s
# Load balancing policy (default: round-robin)
lb_policy least_conn
# Passive failure detection
fail_duration 30s
max_fails 3
}
# Security headers
header {
Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
X-Frame-Options DENY
X-Content-Type-Options nosniff
X-XSS-Protection "1; mode=block"
Referrer-Policy strict-origin-when-cross-origin
Permissions-Policy "geolocation=(), microphone=(), camera=()"
# Hide server information
-Server
}
# Structured JSON access logging to file
log {
output file /var/log/caddy/access.log {
roll_size 100mb
roll_keep 10
roll_keep_for 720h
}
format json
level INFO
}
}
9.2 Multiple Backend Services (Microservices Routing)
api.example.com {
# Route by URL path prefix
handle /auth/* {
reverse_proxy 10.0.1.20:4000
}
handle /users/* {
reverse_proxy 10.0.1.21:4001
}
handle /products/* {
reverse_proxy 10.0.1.22:4002
}
handle /orders/* {
reverse_proxy 10.0.1.23:4003
}
# Fallback: 404 for unmatched paths
handle {
respond "Not Found" 404
}
# Security headers applied globally for this site
header {
Strict-Transport-Security "max-age=63072000; includeSubDomains"
X-Frame-Options DENY
X-Content-Type-Options nosniff
-Server
}
log {
output file /var/log/caddy/api.log
format json
}
}
# Multiple domains — each automatically gets its own TLS cert
www.example.com {
redir https://example.com{uri} permanent
}
example.com {
reverse_proxy localhost:8080
}
9.3 Load Balancing with Multiple Upstreams
app.example.com {
reverse_proxy 10.0.1.10:3000 10.0.1.11:3000 10.0.1.12:3000 {
# Load balancing policy
lb_policy round_robin
# Other options: least_conn, ip_hash, uri_hash, random, random+least_conn
# Weights (Caddy 2.7+)
lb_try_duration 5s # How long to retry before giving up
lb_try_interval 250ms # Interval between retries
# Active health checking (not available in Nginx OSS)
health_uri /healthz
health_interval 10s
health_timeout 5s
health_status 200
# Passive health: remove backend after 3 failures within 30s
fail_duration 30s
max_fails 3
unhealthy_status 500 502 503
# Flush headers immediately (important for SSE / streaming)
flush_interval -1
# Upstream connection keep-alive
transport http {
keepalive 32
keepalive_idle_conns 32
}
# Header rewriting
header_up Host {upstream_hostport}
header_up X-Real-IP {remote_host}
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto {scheme}
}
log {
output file /var/log/caddy/access.log
format json
}
}
9.4 On-Demand TLS (Multi-Tenant SaaS)
This is a Caddy-exclusive feature with no direct Nginx OSS equivalent. Caddy provisions a certificate on the first request for a hostname, making it ideal for platforms where customers bring their own domains.
# Global configuration block
{
# On-demand TLS: Caddy will call this URL to decide whether
# to issue a certificate for a given domain.
# Your backend should return 200 if the domain is valid/registered.
on_demand_tls {
ask https://your-api.internal/check-domain?domain={domain}
burst 5 # Max 5 certificates per interval
interval 2m # Interval for the burst reset
}
}
# Wildcard matcher: catch ALL hostnames
:443 {
tls {
on_demand # Provision cert on first request for each hostname
}
reverse_proxy localhost:8080 {
# Pass the original hostname so your backend knows which tenant
header_up Host {host}
}
}
10. Docker Compose Deployment
Running reverse proxies in Docker is a first-class use case for both servers. The architectures below demonstrate a realistic microservice deployment pattern.
Host Machine ┌─────────────────────────────────────────────────────────┐ │ Docker Network: app_net (bridge) │ │ │ │ ┌─────────────────────────────────────────────────┐ │ │ │ proxy (nginx or caddy) │ │ │ │ Ports: 80→80, 443→443 │ │ │ │ Volumes: ./config, ./certs (nginx) │ │ │ │ ./caddy_data, ./caddy_config (caddy) │ │ │ └────────────────────────┬────────────────────────┘ │ │ │ Docker bridge network │ │ ┌─────────────────┴────────────────┐ │ │ ▼ ▼ │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ app1 │ │ app2 │ │ │ │ (Node.js) │ │ (Python) │ │ │ │ :3000 │ │ :5000 │ │ │ └──────────────┘ └──────────────┘ │ └─────────────────────────────────────────────────────────┘
10.1 Docker Compose with Nginx
services:
# --- Reverse Proxy ---
nginx:
image: nginx:1.26-alpine
container_name: nginx-proxy
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/conf.d:/etc/nginx/conf.d:ro # Site configs
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro # Main config
- ./nginx/certs:/etc/nginx/certs:ro # TLS certificates
- ./nginx/cache:/var/cache/nginx # Proxy cache storage
- nginx_logs:/var/log/nginx
depends_on:
- app1
- app2
networks:
- app_net
# Security: run as non-root (master process still needs root for port 80/443)
# Nginx drops privileges to 'nginx' user for worker processes automatically
healthcheck:
test: ["CMD", "nginx", "-t"]
interval: 30s
timeout: 10s
retries: 3
# --- Backend Application 1 (Node.js) ---
app1:
image: node:20-alpine
container_name: app1
restart: unless-stopped
working_dir: /app
volumes:
- ./app1:/app
command: ["node", "server.js"]
environment:
- NODE_ENV=production
- PORT=3000
expose:
- "3000" # Only visible inside Docker network; NOT published to host
networks:
- app_net
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://localhost:3000/healthz || exit 1"]
interval: 15s
timeout: 5s
retries: 3
# --- Backend Application 2 (Python / FastAPI) ---
app2:
image: python:3.12-slim
container_name: app2
restart: unless-stopped
working_dir: /app
volumes:
- ./app2:/app
command: ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "5000"]
environment:
- PYTHONUNBUFFERED=1
expose:
- "5000"
networks:
- app_net
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:5000/healthz || exit 1"]
interval: 15s
timeout: 5s
retries: 3
volumes:
nginx_logs:
networks:
app_net:
driver: bridge
upstream app1_upstream { server app1:3000; }
upstream app2_upstream { server app2:5000; }
server {
listen 80;
server_name _;
# In Docker, redirect to HTTPS only if you have real TLS certs
# For local testing, proxy directly on HTTP:
location /api/v1/ {
proxy_pass http://app1_upstream/;
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;
}
location /api/v2/ {
proxy_pass http://app2_upstream/;
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;
}
location /healthz {
access_log off;
return 200 "ok\n";
}
}
10.2 Docker Compose with Caddy (Automatic HTTPS)
Caddy's Docker deployment is simpler because there's no separate certificate management step. Caddy persists its certificate data in named Docker volumes.
services:
# --- Reverse Proxy (Caddy) ---
caddy:
image: caddy:2.8-alpine
container_name: caddy-proxy
restart: unless-stopped
ports:
- "80:80"
- "443:443"
- "443:443/udp" # HTTP/3 / QUIC over UDP
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro # Caddyfile config
- caddy_data:/data # Certificates + ACME state (persist!)
- caddy_config:/config # Caddy config cache
depends_on:
- app1
- app2
networks:
- app_net
# Set your ACME email for Let's Encrypt registration
environment:
- ACME_AGREE=true
healthcheck:
test: ["CMD", "caddy", "validate", "--config", "/etc/caddy/Caddyfile"]
interval: 30s
timeout: 10s
retries: 3
# --- Backend Application 1 ---
app1:
image: node:20-alpine
container_name: app1
restart: unless-stopped
working_dir: /app
volumes:
- ./app1:/app
command: ["node", "server.js"]
expose:
- "3000"
networks:
- app_net
# --- Backend Application 2 ---
app2:
image: python:3.12-slim
container_name: app2
restart: unless-stopped
working_dir: /app
volumes:
- ./app2:/app
command: ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "5000"]
expose:
- "5000"
networks:
- app_net
volumes:
caddy_data: # IMPORTANT: This volume stores TLS certificates. Never delete it.
caddy_config:
networks:
app_net:
driver: bridge
# Global config
{
email your@email.com # Let's Encrypt registration email
# Uncomment for staging (testing) to avoid rate limits:
# acme_ca https://acme-staging-v02.api.letsencrypt.org/directory
}
app.example.com {
# Caddy auto-provisions and renews TLS certificate from Let's Encrypt
handle /api/v1/* {
reverse_proxy app1:3000 {
header_up Host {upstream_hostport}
header_up X-Real-IP {remote_host}
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto {scheme}
health_uri /healthz
health_interval 10s
}
}
handle /api/v2/* {
reverse_proxy app2:5000 {
header_up Host {upstream_hostport}
header_up X-Real-IP {remote_host}
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto {scheme}
health_uri /healthz
health_interval 10s
}
}
handle {
respond "Not Found" 404
}
header {
Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
X-Frame-Options DENY
X-Content-Type-Options nosniff
-Server
}
log {
output file /var/log/caddy/access.log
format json
}
}
10.3 Deployment and Testing Commands
# ── Build and start all services (detached) docker compose -f docker-compose.nginx.yml up -d --build # or for Caddy: docker compose -f docker-compose.caddy.yml up -d --build # ── View running containers docker compose ps # ── Follow proxy logs in real-time docker compose logs -f nginx docker compose logs -f caddy # ── Test reverse proxy is forwarding correctly curl -v http://localhost/api/v1/health curl -v http://localhost/api/v2/health # ── Test HTTPS (Caddy auto-provisions cert; replace with your domain) curl -v https://app.example.com/api/v1/health # ── Reload Nginx config without downtime (hot reload) docker compose exec nginx nginx -s reload # ── Reload Caddy config without downtime docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile # ── Check Caddy's TLS certificate status via admin API curl http://localhost:2019/pki/ca/local curl http://localhost:2019/config/ # ── Scale a backend service to 3 replicas docker compose up -d --scale app1=3 # ── Stop everything and preserve volumes docker compose down # ── Stop and DELETE volumes (WARNING: deletes certificates and cache) docker compose down -v
11. Production-Level Considerations
11.1 When to Use Nginx
- High-traffic production workloads where every millisecond and megabyte of RAM matters. Nginx's C implementation and predictable non-GC memory model is a proven choice at scale.
- Complex routing rules requiring fine-grained location matching, map directives, or Lua scripting (via OpenResty).
- Advanced caching as an HTTP cache layer (CDN-lite) in front of origin servers.
- Enterprise environments requiring commercial support (Nginx Plus / F5), compliance guarantees, and a 20-year track record.
- AWS ALB + Nginx on EC2: Common pattern where ALB handles internet-facing TLS termination and distributes to EC2 instances running Nginx as a local reverse proxy to application processes.
- Static content serving at very high throughput alongside proxying.
- WAF integration via ModSecurity module.
11.2 When to Use Caddy
- Small to medium applications where operational simplicity is valuable and automatic HTTPS removes certificate management overhead.
- Developer-facing tooling and internal services where spinning up HTTPS quickly (including on private networks via internal CA) is valuable.
- Multi-tenant SaaS platforms leveraging on-demand TLS for custom domain support.
- Docker / Kubernetes environments where the single-binary, zero-dependency model and JSON API for dynamic reconfiguration simplify deployment.
- Teams without dedicated infrastructure engineers: Caddy's defaults are secure and correct, reducing the operational knowledge required to run a safe reverse proxy.
- HTTP/3 (QUIC): Caddy has stable HTTP/3 support in production; Nginx's HTTP/3 support is experimental as of 1.25.
11.3 SSL Certificate Lifecycle Management
# ── Nginx: Certificate management with Certbot ── # Install certbot and the Nginx plugin sudo apt install certbot python3-certbot-nginx -y # Obtain and install certificate (auto-edits nginx config) sudo certbot --nginx -d app.example.com -d www.app.example.com \ --email your@email.com --agree-tos --non-interactive # Certificates are saved to: # /etc/letsencrypt/live/app.example.com/fullchain.pem # /etc/letsencrypt/live/app.example.com/privkey.pem # Test automatic renewal (dry run — no cert is issued) sudo certbot renew --dry-run # Certbot installs a systemd timer for automatic renewal: sudo systemctl status certbot.timer # Manual force-renewal sudo certbot renew --force-renewal # For wildcard certificates (requires DNS-01 challenge): sudo certbot certonly --dns-cloudflare \ --dns-cloudflare-credentials ~/.secrets/cloudflare.ini \ -d "*.example.com" -d "example.com" # ── Caddy: No manual steps required ── # Caddy handles provisioning, renewal, and OCSP stapling automatically. # Certificates are stored in the caddy_data volume or /var/lib/caddy. # Renewal occurs automatically when less than 30 days remain. # To view Caddy's current certificate information: caddy trust # Show trusted CAs curl localhost:2019/pki/ca/local # Show local CA info (if using internal PKI)
11.4 High Availability
Neither Nginx nor Caddy provides built-in clustering. High availability at the reverse proxy layer is achieved through infrastructure design:
AWS High Availability Architecture
Internet
│
▼
Route 53 (DNS, health-checked failover)
│
▼
AWS Application Load Balancer (ALB)
(Multi-AZ, managed, TLS at this layer optional)
│
├──── AZ ap-south-1a ────────────────────┐
│ ┌────────────────────────────────┐ │
│ │ EC2 / ECS Task │ │
│ │ Nginx or Caddy │ │
│ │ (reverse proxy) │ │
│ └────────────┬───────────────────┘ │
│ │ │
└──── AZ ap-south-1b ────────────────────┘
┌────────────────────────────────┐
│ EC2 / ECS Task │
│ Nginx or Caddy │
│ (reverse proxy) │
└────────────┬───────────────────┘
│
▼
Backend services
(ECS, EKS, Lambda)
Notes:
- ALB health checks remove unhealthy proxy instances from rotation
- Use ASG (Auto Scaling Group) for the proxy tier for self-healing
- For Caddy: share caddy_data (certificate storage) via EFS or S3 backend
to prevent each instance from independently provisioning certs
- For Nginx: share /etc/letsencrypt via EFS; use certbot for renewal
11.5 Performance Optimisation
# /etc/nginx/nginx.conf — Performance tuning
user nginx;
worker_processes auto; # 1 worker per CPU core
worker_cpu_affinity auto; # Pin workers to specific CPUs
worker_rlimit_nofile 65535; # Raise file descriptor limit
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
events {
worker_connections 4096; # Max simultaneous connections per worker
use epoll; # Linux: use epoll (best for high concurrency)
multi_accept on; # Accept as many connections as possible at once
}
http {
sendfile on; # Zero-copy file transfer (bypass kernel buffer)
tcp_nopush on; # Batch TCP packets (combine with sendfile)
tcp_nodelay on; # Disable Nagle algorithm for low latency
keepalive_timeout 65; # Client keep-alive timeout
keepalive_requests 100; # Max requests per keep-alive connection
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json
application/javascript application/rss+xml
application/atom+xml image/svg+xml;
# Buffer sizes (tune for your response sizes)
client_body_buffer_size 16k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
client_max_body_size 10m;
# Upstream keep-alive (reduce connection overhead to backends)
upstream backend {
server 10.0.1.10:3000;
keepalive 64;
}
# Hide Nginx version
server_tokens off;
}
11.6 Security Best Practices
# ── Nginx Security Checklist ──
# 1. Run as non-root user
# user nginx; (default for nginx package)
# 2. Hide server version
# server_tokens off;
# 3. Disable unused HTTP methods
if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE|PATCH)$ ) {
return 405;
}
# 4. Limit request size (prevents oversized POST body attacks)
# client_max_body_size 10m;
# 5. Rate limiting zones (defined in http block)
# limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
# 6. Block access to hidden files
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 7. Required security headers (add_header directives in server block)
# Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options,
# Referrer-Policy, Permissions-Policy
# ── Verify your TLS configuration with SSL Labs ──
# https://www.ssllabs.com/ssltest/analyze.html?d=app.example.com
# ── Scan for common misconfigurations ──
# Mozilla Observatory: https://observatory.mozilla.org/
# ── Caddy Security Defaults (already included out of the box) ──
# - TLS 1.2 minimum
# - Modern cipher suites (no RC4, 3DES, etc.)
# - OCSP stapling enabled
# - HTTP/2 enabled
# - HSTS can be added with one header directive
# - Server header removed by default
11.7 Troubleshooting Common Issues
# ── Nginx Troubleshooting ── # Check config syntax before reloading (prevents bad reload from breaking prod) sudo nginx -t # View last 100 lines of error log in real-time sudo tail -f /var/log/nginx/error.log # Check which nginx process is running ps aux | grep nginx # Check port 80 / 443 binding sudo ss -tlnp | grep ':80\|:443' # Common Nginx 502 Bad Gateway fixes: # 1. Backend is not running → check: systemctl status app / docker ps # 2. Wrong proxy_pass address → check upstream IP/port # 3. Firewall blocking upstream → check: ufw status / sg rules # 4. Upstream timeout → increase proxy_read_timeout # 5. Too many connections → increase worker_connections / keepalive # Test upstream connectivity from Nginx host: curl -v http://10.0.1.10:3000/healthz # Debug headers sent to backend: # Add to location block temporarily: # add_header X-Debug-Upstream "$upstream_addr" always; # ── Caddy Troubleshooting ── # Validate Caddyfile syntax caddy validate --config /etc/caddy/Caddyfile # View structured JSON logs (Caddy default) journalctl -u caddy -f # or if logging to file: tail -f /var/log/caddy/access.log | jq . # Check Caddy admin API curl -s http://localhost:2019/config/ | jq . curl -s http://localhost:2019/reverse_proxy/upstreams | jq . # Caddy ACME / Let's Encrypt issues: # 1. Port 80 must be reachable from the internet (HTTP-01 challenge) # 2. DNS must resolve to your server's IP # 3. Rate limits: max 50 certs/domain/week from Let's Encrypt # 4. Test with staging CA first (acme_ca staging URL in global block) # Force a certificate renewal: caddy run --config /etc/caddy/Caddyfile & curl -X POST http://localhost:2019/pki/ca/local/renew
12. Performance Discussion
12.1 Connection Handling
Nginx uses the epoll system call on Linux (or kqueue on BSD/macOS) to monitor thousands of file descriptors simultaneously with a single system call. This is fundamentally O(1) scalability for connection monitoring — adding connections does not increase the monitoring cost.
Caddy's Go runtime uses similar OS primitives under the hood but wraps them in the Go netpoller, which is called by the Go scheduler as goroutines block on I/O. The overhead of goroutine scheduling is small but measurable compared to raw epoll.
12.2 Memory Utilisation
Nginx's memory advantage is most visible at idle or low-load states. A minimal Nginx installation with two workers might use 10–20 MB of RAM. Caddy's Go runtime requires a base of 30–50 MB even at idle due to the Go runtime itself, the certmagic library, and the HTTP/3 stack. As concurrency increases, the gap narrows — Go goroutines are lean (2–8 KB each), and Caddy handles high concurrency efficiently.
12.3 TLS Performance
Nginx uses OpenSSL (or BoringSSL on some distributions), which is highly optimised for server TLS performance including hardware acceleration (AES-NI, AVX). Caddy uses Go's crypto/tls package, which is well-implemented but historically slightly slower than OpenSSL for bulk TLS operations. The difference in modern deployments is typically <5% for TLS handshake throughput and negligible for keep-alive connections (where the handshake is amortised).
12.4 HTTP/3 and QUIC
This is a genuine technical advantage for Caddy at present. Caddy's HTTP/3 implementation (using the quic-go library) is considered production-stable. Nginx's HTTP/3 support (added in 1.25.0) is still labeled experimental and uses the nginx-quic QUIC library. For applications targeting clients on high-latency or lossy connections (mobile, international users), HTTP/3's reduced handshake latency and head-of-line blocking elimination are meaningful improvements.
12.5 Benchmarking Guidance
Do not rely on this article or any other source's benchmark numbers for infrastructure decisions. Run benchmarks that match your actual traffic pattern — your payload sizes, TLS cipher suite, backend latency, and client connection patterns matter more than synthetic throughput numbers.
# Test realistic HTTPS reverse proxy performance # Install wrk2 (rate-controlled, latency-distribution-accurate) # https://github.com/giltene/wrk2 sudo apt install wrk -y # 60-second test at 1000 req/s constant rate, 100 concurrent # wrk2 gives accurate percentile latencies unlike wrk wrk -t4 -c100 -d60s -R1000 --latency https://your-proxy/api/endpoint # ─── Test SSL handshake throughput specifically ─── # s_time tool (openssl) openssl s_time -connect your-proxy:443 -new -time 30 # -new forces a full handshake each time # ─── Compare request latency at p50/p95/p99 ─── # Install hey go install github.com/rakyll/hey@latest hey -n 50000 -c 100 -h2 https://nginx-proxy/api/endpoint > nginx_results.txt hey -n 50000 -c 100 -h2 https://caddy-proxy/api/endpoint > caddy_results.txt diff nginx_results.txt caddy_results.txt
13. Final Verdict
Use Case │ Recommendation │ Reason ────────────────────────────────────────┼───────────────────┼────────────────────────────────────────────── Small app / side project │ Caddy │ Zero-config HTTPS, simpler ops Personal portfolio / developer tooling │ Caddy │ Fast to set up, automatic cert renewal Multi-tenant SaaS (custom domains) │ Caddy │ On-demand TLS, no Nginx OSS equivalent Docker Compose microservices │ Caddy │ Single binary, JSON API, structured logs Kubernetes Ingress Controller │ Nginx (ingress-nginx) │ Battle-tested, most widely deployed High-traffic production (100k+ rps) │ Nginx │ Proven track record, predictable perf Complex routing / regex / map directives│ Nginx │ More expressive configuration HTTP caching at the proxy layer │ Nginx │ proxy_cache built-in and mature WAF (ModSecurity / web app firewall) │ Nginx │ ngx_http_modsecurity_module Enterprise / compliance required │ Nginx Plus │ Commercial support, active health checks AWS EC2 reverse proxy │ Nginx or Caddy │ Both work; Caddy simplifies cert mgmt AWS ECS / Fargate sidecar proxy │ Caddy │ Single binary, no cert infrastructure needed HTTP/3 (QUIC) in production │ Caddy │ Stable HTTP/3; Nginx HTTP/3 is experimental Mixed workload: static + proxy │ Nginx │ Static file serving + proxy in one config
The honest summary:
- Nginx remains the production standard for high-stakes, complex, high-traffic infrastructure. Its 20-year track record, predictable performance, rich ecosystem, and commercial support path make it the default choice for critical systems.
- Caddy is not a toy — it is production-ready, well-engineered, and genuinely superior for use cases where automatic HTTPS, operational simplicity, structured logging, or on-demand TLS are priorities. The growing Kubernetes and Docker community is increasingly comfortable running Caddy in production.
- They are not mutually exclusive. Many teams use Nginx as their public-facing ingress and Caddy internally for service-to-service communication with mTLS managed by Caddy's internal PKI module.
14. FAQ
Can I migrate from Nginx to Caddy without downtime?
Yes. Run both in parallel — Nginx on port 443 for existing traffic, Caddy on an alternate port. Use an L4 load balancer (AWS NLB) to shift traffic percentage-by-percentage. Validate with synthetic monitoring before cutting fully over. Caddy will independently provision its own Let's Encrypt certificates once it's handling real traffic with DNS pointing to it.
Does Caddy work with internal / private domains?
Yes. For private domains (e.g., app.internal), Caddy's built-in PKI module acts as a local CA, issuing certificates signed by a CA that you can distribute to your internal hosts. This is a first-class feature with zero external dependencies.
Is Nginx inside Kubernetes still the best choice?
The ingress-nginx controller is the most widely deployed Kubernetes ingress, with the largest community and most mature ecosystem. However, Caddy can be run as a Kubernetes ingress controller. For newer clusters where the team is Caddy-familiar, it is a viable choice. For established clusters or complex ingress requirements, ingress-nginx is the safer option.
What about Traefik, HAProxy, Envoy?
This article focuses on Nginx and Caddy as the two most common reverse proxy choices for general-purpose deployment. Traefik is excellent for Docker/Kubernetes with dynamic configuration discovery. HAProxy is a specialist high-performance load balancer. Envoy is a data plane proxy designed for service mesh (Istio, Consul Connect) use cases — it operates at a different level of the stack.
Does Caddy support custom TLS certificates (not Let's Encrypt)?
Yes. Use the tls directive with explicit certificate paths:
app.example.com {
tls /path/to/cert.pem /path/to/key.pem
reverse_proxy localhost:3000
}
How do I handle WebSockets with both servers?
Both servers support WebSocket proxying. The key requirement is passing the Upgrade and Connection headers:
# Nginx — required headers for WebSocket upgrade proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; # Caddy — WebSocket is handled automatically # No special configuration needed; Caddy detects the Upgrade header
15. Conclusion & References
The Nginx vs Caddy decision ultimately comes down to your operational priorities:
- If you value operational simplicity, automatic HTTPS, and modern defaults — start with Caddy.
- If you need proven scale, complex configuration control, built-in caching, or commercial support — Nginx is your foundation.
Both are open source, both are production-proven, and both are actively maintained. The best reverse proxy is the one your team can operate confidently — which means choosing the one you understand well enough to debug at 2 AM.