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)
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 caddymacOS
brew install caddyBuild from source (when extra plugins are needed)
go install github.com/caddyserver/caddy/v2/cmd/caddy@latest
# 或者用 xcaddy 打插件
xcaddy build --with github.com/caddyserver/ratelimitNote 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
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:
- Request a certificate from Let's Encrypt or ZeroSSL (ACME)
- Automatically complete HTTP-01 or TLS-ALPN-01 validation
- Automatically renew before expiry
Common situations that cause automatic HTTPS to fail:
| Symptom | Cause |
|---|---|
Stuck at obtaining certificate | 80/443 is blocked by a firewall or cloud security group |
| Certificate issued successfully but the browser reports a certificate error | Domain DNS does not point to this machine, or the CDN origin configuration in between is incorrect |
| Intranet domain application fails | Intranet domains cannot complete ACME validation and require a DNS-01 challenge or a self-signed certificate |
Only custom certificates (intranet, existing certificates) require tls:
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:
{
local_certs
}4. Reverse Proxy
example.com {
reverse_proxy localhost:8080
}Multiple backends + load balancing strategy:
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-ForandX-Forwarded-Proto; the backend gets the real IP without extra configuration - WebSocket is supported automatically; no
Upgradeheader handling is needed - When the upstream is HTTPS, use
reverse_proxy https://backend:8443; for self-signed certificates addtransport 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:
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:
example.com {
encode zstd gzip
root * /var/www
file_server
}5.2 Common Middleware
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_limitIt 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
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
caddy fmt --overwrite /etc/caddy/Caddyfile6.3 Check Which Directives the Current Binary Supports
caddy list-modules | grep -i ratelimitWhen 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:
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 --browsestarts a service in one line, orcaddy reverse-proxy --from :80 --to :3000 - Multiple sites coexisting: multiple domain blocks written in the same Caddyfile, with certificates requested independently
Related Reading
- Docker from Beginner to Practice: start services with compose and hand them to Caddy for reverse proxying
- Kubernetes Getting Started Guide: ingress and certificates for multi-replica deployments
- Getting Started with Next.js Full-Stack Applications: production deployment methods for frontend services
