Claude
Skills
Sign in
Back

caddy

Included with Lifetime
$97 forever

Caddy v2 reverse proxy with automatic HTTPS. Covers Caddyfile syntax, directives, TLS configuration, DNS challenges, and API-based management. USE WHEN: user mentions "caddy", "caddyfile", "caddy server", "xcaddy", "caddy reverse proxy", asks about "automatic https", "let's encrypt caddy", "caddy tls", "caddy load balancing", "caddy websocket proxy", "caddy dns challenge", "caddy cloudflare", "caddy api", "caddy systemd" DO NOT USE FOR: Nginx-based setups - use `load-balancer` or a dedicated nginx skill, Traefik-based setups - use `traefik` skill, Kubernetes ingress controllers - use `kubernetes` skill, Application-level TLS termination inside app code

Backend & APIs

What this skill does

# Caddy v2 Core Knowledge

## Why Caddy

Caddy v2 is the only production-grade reverse proxy that automatically obtains and
renews TLS certificates from Let's Encrypt or ZeroSSL without any extra configuration.
Compared to Nginx it trades fine-grained buffer/worker tuning for dramatically simpler
configuration and zero-touch certificate management.

| Capability | Caddy | Nginx |
|---|---|---|
| Automatic TLS (ACME) | Built-in, zero config | Requires certbot + cron |
| Certificate renewal | Automatic, in-process | External cronjob |
| HTTP/2 and HTTP/3 | Enabled by default | HTTP/3 requires extra build |
| Config syntax | Caddyfile (concise) | nginx.conf (verbose) |
| Dynamic config reload | API + `caddy reload` | `nginx -s reload` |
| Plugin ecosystem | xcaddy custom builds | Third-party modules |
| Worker/buffer tuning | Limited | Very granular |
| Established ecosystem | Growing | Mature, wide adoption |

**Choose Caddy when**: you want automatic cert management, a simpler config, or HTTP/3.
**Choose Nginx when**: you need granular buffer tuning, established module ecosystem,
or are joining an existing Nginx-heavy team.

---

## Caddyfile Structure

```caddyfile
# Global options block — applies to all sites
{
    email [email protected]          # ACME registration email (REQUIRED for Let's Encrypt)
    acme_ca https://acme-v02.api.letsencrypt.org/directory   # default, can switch to ZeroSSL
    # acme_ca https://acme.zerossl.com/v2/DV90               # ZeroSSL alternative

    # Admin API endpoint (default: localhost:2019)
    admin localhost:2019

    # Global default log level
    log {
        level INFO
    }

    # Optional: use a specific ACME EAB for ZeroSSL
    # acme_eab key_id=<id> mac_key=<key>

    # Optional: staging CA for testing (avoids rate limits)
    # acme_ca https://acme-staging-v02.api.letsencrypt.org/directory
}

# Snippet definition — reusable block of directives
(secure_headers) {
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
        X-Content-Type-Options "nosniff"
        X-Frame-Options "DENY"
        Referrer-Policy "strict-origin-when-cross-origin"
        -Server                   # Remove Server header
    }
}

(gzip_encode) {
    encode zstd gzip {
        minimum_length 1024
    }
}

# Site block — matches by hostname
example.com {
    import secure_headers
    import gzip_encode

    reverse_proxy localhost:3000
}

# Multiple hostnames in one block
api.example.com api-v2.example.com {
    import secure_headers
    reverse_proxy localhost:4000
}

# Redirect www to non-www
www.example.com {
    redir https://example.com{uri} permanent
}
```

---

## Multi-App Server (Multiple Domains and Subdomains)

```caddyfile
{
    email [email protected]
    admin localhost:2019
}

(common) {
    encode zstd gzip
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
        X-Content-Type-Options "nosniff"
        X-Frame-Options "SAMEORIGIN"
        X-XSS-Protection "1; mode=block"
        -Server
    }
}

# Main marketing site (static files)
company.com www.company.com {
    redir https://company.com{uri} 308  # Permanent redirect www → apex
    import common
    root * /var/www/company
    file_server
    try_files {path} /index.html        # SPA fallback
}

# Node.js API backend
api.company.com {
    import common

    reverse_proxy localhost:3001 {
        health_uri   /health
        health_interval 10s
        health_timeout  5s
        health_status   200

        # Timeouts
        transport http {
            dial_timeout       5s
            response_header_timeout 30s
            keepalive          30s
            keepalive_idle_conns 32
        }

        # Headers passed to upstream
        header_up X-Real-IP {remote_host}
        header_up X-Forwarded-Proto {scheme}
        header_up X-Request-ID {http.request.uuid}
        header_down -X-Powered-By    # Remove revealing header
    }
}

# Python Django admin app
admin.company.com {
    import common
    basicauth /* {
        # htpasswd -nbB admin password | cut -d: -f2
        admin $2y$10$...hashed_password_here...
    }
    reverse_proxy localhost:8000
}

# Grafana dashboard
grafana.company.com {
    import common
    reverse_proxy localhost:3000 {
        header_up Host {upstream_hostport}
    }
}

# Static asset CDN edge (file server with aggressive caching)
static.company.com {
    import common
    root * /var/www/static
    file_server {
        hide .git .env
    }
    header Cache-Control "public, max-age=31536000, immutable"
}
```

---

## WebSocket Proxy

```caddyfile
app.example.com {
    # Regular HTTP routes
    handle /api/* {
        reverse_proxy localhost:3000
    }

    # WebSocket route — Caddy auto-detects Upgrade header
    handle /ws/* {
        reverse_proxy localhost:3001 {
            transport http {
                # WebSocket connections need longer timeouts
                dial_timeout            5s
                response_header_timeout 0s   # 0 = no timeout (needed for WS)
                read_timeout            0s
                write_timeout           0s
            }
            # Keep WebSocket headers
            header_up Connection {http.request.header.Connection}
            header_up Upgrade    {http.request.header.Upgrade}
        }
    }

    # Catch-all — serve SPA
    handle {
        root * /var/www/app
        try_files {path} /index.html
        file_server
    }
}
```

---

## TLS and DNS Challenge (Cloudflare)

Wildcard certificates require a DNS challenge. Use `xcaddy` to build Caddy with the
Cloudflare DNS provider plugin.

```bash
# Build Caddy with Cloudflare DNS plugin
xcaddy build --with github.com/caddy-dns/cloudflare

# Move to PATH
sudo mv caddy /usr/local/bin/caddy
sudo setcap cap_net_bind_service=+ep /usr/local/bin/caddy
```

```caddyfile
# Environment variable substitution in Caddyfile
{
    email [email protected]
    acme_dns cloudflare {env.CLOUDFLARE_API_TOKEN}
}

# Wildcard cert — works for all subdomains
*.example.com example.com {
    tls {
        dns cloudflare {env.CLOUDFLARE_API_TOKEN}
        # Optional: restrict to ZeroSSL
        # ca https://acme.zerossl.com/v2/DV90
    }

    @api host api.example.com
    handle @api {
        reverse_proxy localhost:3000
    }

    @app host app.example.com
    handle @app {
        reverse_proxy localhost:4000
    }

    # Default — 404
    handle {
        respond "Not Found" 404
    }
}
```

Environment file `/etc/caddy/caddy.env`:
```bash
CLOUDFLARE_API_TOKEN=your_cloudflare_api_token_here
```

Systemd unit picks up env file:
```ini
[Service]
EnvironmentFile=/etc/caddy/caddy.env
```

---

## Load Balancing

```caddyfile
api.example.com {
    reverse_proxy {
        to localhost:3001 localhost:3002 localhost:3003

        # Load balancing policy
        lb_policy least_conn          # round_robin | least_conn | ip_hash | uri | random

        # Passive health checks (no extra requests)
        fail_duration     30s        # How long to mark upstream as down
        max_fails         3          # Fails before marking down
        unhealthy_latency 5s         # Mark down if response > 5 s

        # Active health checks (probe endpoint)
        health_uri      /health
        health_interval 15s
        health_timeout  3s
        health_status   200

        # Circuit breaker retry
        # Try next upstream on these errors
        transport http {
            dial_timeout 3s
            response_header_timeout 15s
        }
    }
}
```

---

## Rate Limiting (with caddy-ratelimit plugin)

```bash
xcaddy build --with github.com/mholt/caddy-ratelimit
```

```caddyfile
api.example.com {
    rate_limit {
        zone api_zone {
            key    {remote_host}
            window 1m
            events 100
        }
    }
    reverse_proxy localhost:3000
}
```

---

## Caddy Admin API

```bash
# Reload config without restart
caddy reload --config /etc/caddy/Ca

Related in Backend & APIs