Caddyfile 语法
site block、directive、全局选项。
35 分钟
Caddyfile 语法
Caddyfile 是 Caddy 的声明式配置格式:按 站点块(site block) 组织,块内写 指令(directive)。比 ngx-config 的 server/location 更紧凑,HTTPS 常可省略。
学习目标
- 读懂 site block、directive 与 matcher 基础
- 配置全局选项块
{ ... } - 将 Nginx
location概念映射到 Caddyhandle/route
核心内容
最小站点块
# /etc/caddy/Caddyfile
www.coderoadmap.cn {
respond "CodeRoadMap via Caddy"
}
Caddy 见到域名即 自动申请 HTTPS(需 80/443 可达且 DNS 正确,见 dns-essentials)。
全局选项
{
email admin@coderoadmap.cn
# acme_ca https://acme-staging-v02.api.letsencrypt.org/directory # 测试用
}
www.coderoadmap.cn {
encode gzip
log {
output file /var/log/caddy/access.log
}
}
email 供 Let's Encrypt 账户通知;encode 类似 Nginx gzip on。
路径匹配与 handle
www.coderoadmap.cn {
handle /api/* {
reverse_proxy 127.0.0.1:8080
}
handle {
reverse_proxy 127.0.0.1:3000
}
}
handle /api/*:前缀匹配,类似location /api/- 无路径的
handle:兜底,类似location / - 多个
handle按定义顺序 匹配,先写更具体的路径
常用指令对照
| Nginx | Caddyfile |
|---|---|
proxy_pass | reverse_proxy |
root + try_files | root + file_server / try_files |
return 301 | redir https://... |
listen 443 ssl | 站点域名即启用 TLS(自动) |
练习
- 写含全局 与两个 的 Caddyfile 并