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. (For an end-to-end breakdown of how requests navigate DNS and edge CDNs before reaching your proxy, see From DNS to CDNs: Demystifying Modern Web Infrastructure.)

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.
reverse-proxy-flow.diagram
  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-architecture.diagram
  ┌─────────────────────────────────────────────────────┐
  │                 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.28.x (released April 2025); mainline 1.29.x.
  • For an operational guide on Nginx caching and core modules, see Demystifying Nginx: Server, Proxy, Load Balancer & Cache.

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.diagram
  ┌───────────────────────────────────────────────────────┐
  │                  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:2019 for 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.9.x (check GitHub Releases for the latest patch).

4. How Reverse Proxy Architecture Works

When a client makes a request, the reverse proxy performs several operations in sequence:

request-lifecycle.diagram
  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

architecture-comparison.diagram
  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, or vegeta against your specific workload before making a decision on performance grounds.

benchmarking-commands.sh
# 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.

tls-comparison.table
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       │ Via xcaddy DNS module *
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        │ Via xcaddy DNS module *
On-demand TLS                │ Not available             │ Available (dynamic cert)
Internal CA (mTLS)           │ Manual setup              │ Built-in PKI module

* DNS-01 for Caddy requires a provider-specific module compiled via xcaddy.
  Standard Caddy binary supports HTTP-01 and TLS-ALPN-01 out of the box.

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

lb-comparison.table
Algorithm               │ Nginx (OSS)   │ Nginx Plus  │ Caddy
────────────────────────┼───────────────┼─────────────┼──────────────
Round-robin             │ ✅ (default)  │ ✅          │ ✅ (round_robin)
Random                  │ ❌            │ ✅          │ ✅ (default: random)
Least connections       │ ✅ (least_conn)│ ✅         │ ✅ (least_conn)
IP hash (sticky)        │ ✅ (ip_hash)  │ ✅          │ ✅ (ip_hash / client_ip_hash)
Weighted                │ ✅ (weight=N) │ ✅          │ ✅ (weighted_round_robin)
First available         │ ❌            │ ✅          │ ✅ (first)
Random choice of two    │ ❌            │ ✅ (random) │ ✅ (random_choose 2)
Active health checks    │ ❌            │ ✅          │ ✅ (health_uri)
Passive health checks   │ ✅ (max_fails)│ ✅          │ ✅ (fail_duration)
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 modsecurity WAF module integrates via ngx_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-security plugin 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

observability-comparison.table
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 via worker_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.
full-feature-matrix.table
Category              │ Nginx (OSS 1.28)        │ Caddy 2.9
──────────────────────┼─────────────────────────┼─────────────────────────
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         │ ✅ (stable since 1.28)  │ ✅ (stable)
Memory footprint      │ Very low (~few MB/worker)│ Low (varies by workload)
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

install-nginx.sh
# Update package index
sudo apt update

# Install Nginx from Ubuntu's upstream-synced repo (older version)
sudo apt install nginx -y

# Verify installation
nginx -v
# nginx version: nginx/1.24.0 (Ubuntu)  ← Ubuntu's bundled version

# 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.28.x) ---
# Install prerequisites
sudo apt install -y curl gnupg2 ca-certificates lsb-release ubuntu-keyring

# Import signing key
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
  | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

# Verify key fingerprint (must match: 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62)
gpg --dry-run --quiet --import --import-options import-show \
  /usr/share/keyrings/nginx-archive-keyring.gpg

# Add official stable repo for Ubuntu Noble (24.04)
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

# Pin official packages above Ubuntu's bundled version
printf "Package: nginx\nPin: origin nginx.org\nPin-Priority: 900\n" \
  | sudo tee /etc/apt/preferences.d/99nginx

sudo apt update && sudo apt install nginx -y

# Verify updated version (should show 1.28.x)
nginx -v

7.2 Install Caddy

install-caddy.sh
# 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.

/etc/nginx/conf.d/app.conf
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 Referrer-Policy           "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy        "geolocation=(), microphone=(), camera=()" always;
    # Content-Security-Policy: modern defense against XSS (replaces deprecated X-XSS-Protection)
    add_header Content-Security-Policy   "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';" always;

    # --- Trusted Proxy Configuration (Prevent IP Spoofing) ---
    # When deployed behind an AWS ALB or Cloudflare, only trust real client IP from upstream proxy CIDR:
    # set_real_ip_from  10.0.0.0/16;          # VPC CIDR or ALB subnet
    # real_ip_header     X-Forwarded-For;
    # real_ip_recursive  on;

    # --- 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

/etc/nginx/conf.d/upstream.conf
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 with weights and passive health check parameters
    # Passive health checking (Nginx OSS): Marks a server unavailable for fail_timeout (30s)
    # after max_fails (3) consecutive failed attempts on real client traffic.
    # Active health checking (periodic synthetic probes) is an Nginx Plus exclusive feature.
    server 10.0.1.10:3000 weight=3 max_fails=3 fail_timeout=30s;
    server 10.0.1.11:3000 weight=1 max_fails=3 fail_timeout=30s;
    server 10.0.1.12:3000 weight=1 max_fails=3 fail_timeout=30s;

    # Keep-alive connections to backend pool (reduces TCP/TLS handshake latency)
    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)

/etc/nginx/conf.d/microservices.conf
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

/etc/nginx/nginx.conf (http block)
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.

/etc/caddy/Caddyfile
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 is random; setting least_conn here)
        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
        Referrer-Policy           strict-origin-when-cross-origin
        Permissions-Policy        "geolocation=(), microphone=(), camera=()"
        Content-Security-Policy   "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';"
        # Hide server identification
        -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)

/etc/caddy/Caddyfile — microservices
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

/etc/caddy/Caddyfile — load balancing
app.example.com {
    reverse_proxy 10.0.1.10:3000 10.0.1.11:3000 10.0.1.12:3000 {
        # Load balancing policy (Caddy default is 'random'; here explicitly using 'round_robin')
        lb_policy       round_robin
        # Other official policies: random (default), least_conn, first, ip_hash, client_ip_hash, uri_hash, random_choose 2, weighted_round_robin

        # Retries
        lb_try_duration  5s      # How long to retry before giving up
        lb_try_interval  250ms   # Interval between retries

        # Active health checking (periodic synthetic probes out-of-band)
        health_uri      /healthz
        health_interval 10s
        health_timeout  5s
        health_status   200

        # Passive health checking (monitors actual runtime failures)
        fail_duration   30s
        max_fails       3
        unhealthy_status 5xx

        # 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.

/etc/caddy/Caddyfile — on-demand TLS
# 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.

docker-deployment.diagram
  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

docker-compose.nginx.yml
services:

  # --- Reverse Proxy ---
  nginx:
    image: nginx:1.28-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
nginx/conf.d/app.conf (for Docker)
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.

docker-compose.caddy.yml
services:

  # --- Reverse Proxy (Caddy) ---
  caddy:
    image: caddy:2.9-alpine
    container_name: caddy-proxy
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
      - "443:443/udp"   # HTTP/3 / QUIC over UDP
      - "127.0.0.1:2019:2019" # Caddy Admin API (bound only to host loopback for security)
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro  # Caddyfile config
      - caddy_data:/data                     # Certificates + ACME state (crucial to persist!)
      - caddy_config:/config                 # Caddy runtime config cache
    depends_on:
      - app1
      - app2
    networks:
      - app_net
    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
Caddyfile (for Docker)
# 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

deployment-commands.sh
# ── 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 and configuration via Admin API
# From host (when 127.0.0.1:2019 is mapped):
curl http://localhost:2019/config/ | jq .
# Or executed directly inside container (if admin port not exposed to host):
docker compose exec caddy curl -s http://localhost:2019/config/ | jq .
docker compose exec caddy curl -s http://localhost:2019/reverse_proxy/upstreams | jq .

# ── 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-certbot-automation.sh
# ── 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: Automatic Certificate Management & DNS-01 Requirements ──
# Caddy handles provisioning, renewal, and OCSP stapling automatically via CertMagic.
# Certificates are stored in /var/lib/caddy or the caddy_data volume.
# Renewal occurs automatically in the background when 30 days of lifetime remain.

# Note on DNS-01 and Wildcard Certificates:
# The standard Caddy binary supports HTTP-01 and TLS-ALPN-01 out of the box.
# If you require wildcard certificates (*.example.com) or cannot expose port 80/443 publicly,
# you must compile Caddy with your DNS provider's module using xcaddy:
# xcaddy build --with github.com/caddy-dns/cloudflare
# (or with route53: --with github.com/caddy-dns/route53)

# Caddy trust command:
# Installs Caddy's root certificate for its default local internal CA into
# the system and browser trust stores (essential for local HTTPS / internal testing):
caddy trust

# Inspect local PKI CA information:
curl http://localhost:2019/pki/ca/local | jq .

11.4 High Availability

Neither Nginx nor Caddy provides built-in clustering. High availability at the reverse proxy layer is achieved through infrastructure design:

high-availability.diagram
  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 automatically
  - Auto Scaling Groups (ASG) ensure automatic replacement of failed instances
  - Multi-instance Caddy requires shared ACME storage (e.g. S3 plugin or Amazon EFS)
    so instances coordinate TLS renewals and avoid Let's Encrypt rate limits
  - Multi-instance Nginx can terminate TLS at the ALB via AWS Certificate Manager (ACM),
    or share /etc/letsencrypt on Amazon EFS with a single master instance executing certbot

Shared Certificate Storage for Multi-Instance Caddy

In auto-scaled AWS environments (ECS Fargate or EC2 ASG), running multiple Caddy replicas requires a shared storage module so all instances share issued certificates and coordinate ACME challenges without duplicating requests or hitting CA rate limits. This is configured in the global options block using plugins like caddy-storage-s3 or caddy-tlsredis:

Caddyfile — s3-shared-storage
# Global options block with S3 shared storage plugin
{
    storage s3 {
        bucket          "my-caddy-tls-certificates"
        region          "ap-south-1"
        prefix          "caddy"
        # Uses AWS IAM Role attached to ECS Task or EC2 instance profile
    }
}

Observability: Prometheus Metrics & CloudWatch Logging

  • Caddy: Exposes native Prometheus metrics out of the box at http://localhost:2019/metrics without sidecars or extra modules. In Docker or ECS, send logs via the awslogs log driver; since Caddy emits structured JSON by default, CloudWatch Logs Insights can immediately query fields like status, duration, and remote_ip without regex parsing.
  • Nginx: Emits unstructured or custom log lines that require a custom log_format for JSON output. Prometheus monitoring requires running the nginx-prometheus-exporter sidecar alongside Nginx, querying the /stub_status endpoint. For more details on system-level metrics, see our guide on Linux Performance Tuning.

11.5 Performance Optimisation

nginx-performance-tuning.conf
# /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

security-checklist.sh
# ── 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

troubleshooting.sh
# ── 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 kernel monitoring cost.

Caddy's Go runtime uses similar OS primitives under the hood via the Go netpoller, which integrates directly with the Go runtime scheduler. When a goroutine blocks on network I/O, the netpoller parks the goroutine and wakes it when the descriptor is ready. Go's M:N scheduler distributes millions of goroutines across OS threads with minimal context-switch overhead.

12.2 Memory and Resource Utilisation

Resource utilization differs primarily because of the underlying language runtimes and memory management strategies:

  • Nginx (C, manual memory management): Allocates memory pools per connection and request. Because it lacks a garbage collector, memory footprint is deterministic, minimal, and unaffected by GC pauses. Under sustained high connection volumes, memory usage scales linearly with connection socket buffer configurations.
  • Caddy (Go, automatic garbage collection): Leverages goroutines that typically start with a small ~2–4 KB stack, expanding dynamically as needed. The Go runtime maintains heap allocations and executes concurrent, low-latency garbage collection cycles. While total resident set size (RSS) is typically higher than Nginx at idle due to runtime overhead and runtime pools, Caddy efficiently handles hundreds of thousands of concurrent connections under production conditions.

12.3 TLS Performance and Session Handling

Both proxies deliver high-throughput TLS termination leveraging modern cryptographic hardware acceleration:

  • Nginx: Links against OpenSSL (or BoringSSL), utilizing hand-optimized C and assembly implementations of modern cipher suites (such as AES-GCM and ChaCha20-Poly1305) with Intel AVX and AES-NI hardware acceleration.
  • Caddy: Uses Go's standard crypto/tls library, which features pure Go and assembly implementations of standard ciphers. In real-world workloads with HTTP keep-alive, TLS session resumption (session IDs and session tickets), and TLS 1.3 0-RTT handshakes, the cryptographic overhead is amortized over thousands of requests, rendering differences in TLS computational cost negligible compared to upstream and network latency.

12.4 HTTP/3 and QUIC Support

Both Nginx and Caddy now provide stable production implementations of HTTP/3 and QUIC over UDP:

  • Caddy: Supported HTTP/3 early through the mature quic-go library, enabling 0-RTT handshakes and connection migration across networks (e.g. mobile switching from Wi-Fi to cellular) by default.
  • Nginx: Features native HTTP/3 and QUIC support merged into mainline and graduated to the 1.28 stable release, complete with CUBIC and BBR congestion control configurations.

12.5 Benchmarking Methodology & Reproducibility

DevOps Principle: Never base architectural decisions on synthetic vendor-published benchmarks. Synthetic benchmarks running over localhost or identical virtual networks test CPU looping and socket buffer recycling rather than real-world conditions. Always execute tests reflecting your actual network latency, TLS cipher suite, response body size distribution, and connection reuse patterns.

When measuring reverse proxy latency distributions, avoid the Coordinated Omission trap. Tools like standard wrk or ab wait for a response before issuing the next request, which artificially masks tail latencies when the server stalls. Use rate-controlled testing tools like wrk2 or vegeta:

realistic-benchmark.sh
# ── Tool 1: wrk (High-concurrency connection stress test) ──
# Install standard wrk on Ubuntu
sudo apt install wrk -y

# 30-second concurrency test: 4 threads, 400 connections, testing HTTP keep-alive
wrk -t4 -c400 -d30s --latency https://your-proxy-domain.com/api/v1/health

# ── Tool 2: wrk2 (Constant-throughput test to measure accurate p95/p99 tail latency) ──
# Compile wrk2 from source (required for constant-throughput testing with -R)
sudo apt install -y build-essential libssl-dev git zlib1g-dev
git clone https://github.com/giltene/wrk2.git /tmp/wrk2
cd /tmp/wrk2 && make && sudo cp wrk /usr/local/bin/wrk2

# Run at a controlled target rate of 2,000 requests/sec with 100 concurrent clients:
wrk2 -t4 -c100 -d60s -R2000 --latency https://your-proxy-domain.com/api/v1/health

# ── Tool 3: hey (Quick percentile latency inspection with HTTP/2) ──
go install github.com/rakyll/hey@latest
hey -n 50000 -c 100 -h2 https://your-proxy-domain.com/api/v1/health

# ── Tool 4: OpenSSL s_time (Isolate raw TLS handshake throughput without HTTP payload) ──
openssl s_time -connect your-proxy-domain.com:443 -new -time 30

13. Final Verdict

decision-matrix.table
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 / Gateway API        │ Gateway API / F5  │ Community ingress-nginx retired in March 2026; adopt Gateway API
High-traffic production (100k+ rps)     │ Nginx             │ Proven track record, deterministic C performance
Complex routing / regex / map directives│ Nginx             │ Highly expressive configuration language
HTTP caching at the proxy layer         │ Nginx             │ Built-in proxy_cache with background updates
WAF (ModSecurity / web app firewall)    │ Nginx             │ ngx_http_modsecurity_module integration
Enterprise / compliance required        │ Nginx Plus        │ Commercial support, active health checks, JWT auth
AWS EC2 reverse proxy                   │ Nginx or Caddy    │ Both work well; Caddy automates certificate lifecycles
AWS ECS / Fargate sidecar proxy         │ Caddy             │ Single binary, no external cert management needed
HTTP/3 (QUIC) in production             │ Caddy or Nginx    │ Stable in Caddy 2.9+ and Nginx 1.28+
Mixed workload: static files + proxy    │ Nginx             │ Direct kernel sendfile static serving + proxy in one

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

What is the status of Nginx in Kubernetes after the March 2026 ingress-nginx retirement?

In March 2026, the Kubernetes project and SIG Network officially retired and archived the community-maintained kubernetes/ingress-nginx repository. The project suffered from severe maintainer burnout and architectural debt around legacy annotations. Crucially, this retirement applies only to the community project — F5’s independently maintained NGINX Ingress Controller (available in both open-source and NGINX Plus editions) remains actively supported and regularly patched.

For modern Kubernetes deployments, the recommended path forward is migrating to the Kubernetes Gateway API (using implementations like Envoy Gateway, Cilium Gateway API, or Istio) or adopting maintained controllers like Traefik or F5 NGINX.

How do I prevent X-Forwarded-For client IP spoofing in Nginx and Caddy?

If your reverse proxy trusts X-Forwarded-For unconditionally, any malicious client can send a fabricated header (e.g. X-Forwarded-For: 127.0.0.1) to bypass IP-based rate limiting or access controls.

  • In Nginx: Use set_real_ip_from <trusted-proxy-cidr>; and real_ip_header X-Forwarded-For;. Nginx will discard untrusted client-supplied headers and only record the IP forwarded by your trusted load balancer.
  • In Caddy: Configure the global servers { trusted_proxies static <cidr> } block. Caddy will parse the true client IP through trusted hops only and expose it via {client_ip}.

Why does Caddy require an external module for DNS-01 and wildcard certificates?

Standard Caddy binaries include only the HTTP-01 and TLS-ALPN-01 ACME challenge types because they require no external DNS API credentials. To obtain wildcard certificates (e.g. *.example.com) or issue certificates for air-gapped/internal machines, you must authenticate ownership by writing DNS TXT records. Because each DNS provider (Cloudflare, AWS Route 53, DigitalOcean, Google Cloud DNS) uses a proprietary API, Caddy isolates these integrations into modular provider plugins built via xcaddy.

How does Caddy handle high availability when running multiple instances?

By default, Caddy stores certificates in the local filesystem. If you run multiple instances behind an AWS ALB or NLB without coordination, each instance will independently attempt ACME handshakes, leading to race conditions and triggering Let's Encrypt rate limits (50 certificates per registered domain per week). In multi-instance deployments, configure a shared storage module such as caddy-storage-s3, caddy-tlsredis, or an Amazon EFS mount so all nodes share issued certificates and lock ACME orders cooperatively.

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 or secondary IP. 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 receives 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 local root CA. Run caddy trust to install Caddy's root certificate into the local system and browser trust store.

Does Caddy support custom TLS certificates (not Let's Encrypt)?

Yes. Use the tls directive with explicit certificate paths:

Caddyfile — custom cert
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:

websocket-config
# 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 and tunnels traffic automatically

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.

Related DevOps Guides on This Portfolio

Official Documentation and Authoritative References