Skip to content

Getting Started with Caddy: Automatic HTTPS and Reverse Proxy ​

Caddy automatically requests and renews certificates by default; once the domain is configured, it works. The prerequisites are that ports 80/443 are publicly accessible and the required modules are actually compiled into the binary—these two points determine whether following a tutorial will get stuck.

How Caddy Differs from Other Web Servers ​

Caddy is written in Go, and its biggest difference from Nginx/Apache is its default behavior:

  • After the domain is configured, it automatically requests and renews certificates, with no extra TLS directives needed
  • The configuration file is the Caddyfile (there is also a native JSON format); dozens of lines can express common requirements
  • A single binary, with plugins selected at compile time (this differs from Nginx's modular approach and leads to the "directive exists but is unavailable" issue, see 6.3)

Trade-off: plugins must be custom-compiled, and xcaddy build is a common operation.

1. Installation ​

Debian/Ubuntu (official repository, recommended)

bash
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddy

macOS

bash
brew install caddy

Build from source (when extra plugins are needed)

bash
go install github.com/caddyserver/caddy/v2/cmd/caddy@latest
# 或者用 xcaddy 打插件
xcaddy build --with github.com/caddyserver/ratelimit

Note that the old go get usage is no longer used to install executables after Go 1.17; go install ...@version is the current method.

2. Minimal Caddyfile Example ​

caddyfile
example.com {
    root * /var/www/example.com
    file_server
}

Three things: match the domain, set the root directory, and enable static file serving.

* here means "match all requests"; it is a path matcher, not a wildcard domain.

3. Automatic HTTPS: When It Is Triggered ​

No tls directive is needed. As long as a domain appears in the Caddyfile (and 80/443 are publicly accessible), Caddy will:

  1. Request a certificate from Let's Encrypt or ZeroSSL (ACME)
  2. Automatically complete HTTP-01 or TLS-ALPN-01 validation
  3. Automatically renew before expiry

Common situations that cause automatic HTTPS to fail:

SymptomCause
Stuck at obtaining certificate80/443 is blocked by a firewall or cloud security group
Certificate issued successfully but the browser reports a certificate errorDomain DNS does not point to this machine, or the CDN origin configuration in between is incorrect
Intranet domain application failsIntranet domains cannot complete ACME validation and require a DNS-01 challenge or a self-signed certificate

Only custom certificates (intranet, existing certificates) require tls:

caddyfile
internal.example.com {
    tls /etc/caddy/certs/cert.pem /etc/caddy/certs/key.pem
    root * /var/www
    file_server
}

To use Caddy self-signed certificates locally/on an intranet:

caddyfile
{
    local_certs
}

4. Reverse Proxy ​

caddyfile
example.com {
    reverse_proxy localhost:8080
}

Multiple backends + load balancing strategy:

caddyfile
example.com {
    reverse_proxy 10.0.0.1:8080 10.0.0.2:8080 {
        lb_policy round_robin   # 可选 least_conn / ip_hash / random / first
        health_uri /health
        health_interval 10s
    }
}

A few practical points about reverse proxy:

  • Automatically forwards X-Forwarded-For and X-Forwarded-Proto; the backend gets the real IP without extra configuration
  • WebSocket is supported automatically; no Upgrade header handling is needed
  • When the upstream is HTTPS, use reverse_proxy https://backend:8443; for self-signed certificates add transport http { tls_insecure_skip_verify } (test environments only)

5. Routing and Middleware ​

Caddy directives execute in a fixed order (encode → reverse_proxy, etc., have built-in ordering); use route when you need to force a custom order:

caddyfile
example.com {
    route /api/* {
        reverse_proxy localhost:8080
    }
    route {
        root * /var/www/example.com
        file_server
    }
}

5.1 Compression ​

The gzip directive has been replaced by encode in v2:

caddyfile
example.com {
    encode zstd gzip
    root * /var/www
    file_server
}

5.2 Common Middleware ​

caddyfile
example.com {
    # 安全响应头
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains"
        X-Content-Type-Options "nosniff"
        X-Frame-Options "DENY"
        -Server
    }

    # 访问日志(JSON 行格式)
    log {
        output file /var/log/caddy/access.log {
            roll_size 50mb
            roll_keep 5
        }
    }

    # 静态压缩文件优先
    root * /var/www
    file_server {
        precompressed zstd gzip
    }
}

5.3 rate_limit Is Not a Built-in Directive ​

Writing rate_limit directly gives:

Error: adapting config using caddyfile: unrecognized directive: rate_limit

It comes from the third-party plugin github.com/mholt/caddy-ratelimit and must be recompiled with xcaddy build --with github.com/mholt/caddy-ratelimit. This is the most common reason for "the tutorial works, but my machine errors"—Caddy's directive set depends on which modules were selected at compile time; caddy list-modules can list what the current binary actually has.

6. Operations Essentials ​

6.1 Validate First, Then Reload ​

bash
caddy validate --config /etc/caddy/Caddyfile   # 只校验,不生效
sudo systemctl reload caddy                    # 平滑重载,不断连接

Running restart directly after changing the configuration interrupts connections; reload is the zero-downtime way. validate can catch syntax errors before reloading and avoid the service failing to start.

6.2 Formatting ​

bash
caddy fmt --overwrite /etc/caddy/Caddyfile

6.3 Check Which Directives the Current Binary Supports ​

bash
caddy list-modules | grep -i ratelimit

When troubleshooting "directive not recognized", first confirm whether the module exists, then suspect syntax.

6.4 Admin API ​

Caddy exposes the config API at localhost:2019; caddy reload actually POSTs the config to it:

bash
curl localhost:2019/config/          # 查看当前生效配置
curl localhost:2019/metrics          # Prometheus 指标

This endpoint is also the entry point for dynamic configuration in containerized deployments.

7. Typical Uses ​

  • Static sites / blogs: root + file_server, with fully automatic certificates
  • Reverse proxy: expose intranet services (panels, APIs, database admin interfaces) to a domain, eliminating a separate Nginx
  • Local development: caddy file-server --browse starts a service in one line, or caddy reverse-proxy --from :80 --to :3000
  • Multiple sites coexisting: multiple domain blocks written in the same Caddyfile, with certificates requested independently

References ​

Last updated: