caddy速查
基础结构
# 格式:<监听地址> 或 <域名> [端口]
example.com, www.example.com {
# 站点配置写在这里
}
- 域名:Caddy 自动申请并管理 TLS 证书。
- IP/端口:用于监听指定地址。
TLS / HTTPS
example.com {
tls yourmail@example.com # 自动证书申请时的联系邮箱
}
绑定 IP
example.com {
bind 1.2.3.4 # 只监听特定 IP
}
静态文件服务
example.com {
file_server # 启用静态文件服务
root * /var/www/site # 设置站点根目录
}
⚠️ 顺序很重要:file_server 在后,必须 root 在前,否则会报错或无法找到文件。
重定向
# IP 访问强制跳转到域名
http://8.8.8.8:80, http://[2001:4860:4860::8888]:80 {
redir https://blog.example.com
}
# HTTP → HTTPS
http://example.com {
redir https://example.com{uri}
}
路由 / 匹配
handle / handle_path
example.com {
# 与 location 类似,分路径处理
handle_path /app/* {
file_server
root * /var/www/app
}
handle_path /api/* {
reverse_proxy localhost:3000
}
}
handle:路径不会自动裁剪(/api/foo→/api/foo)。handle_path:会去掉匹配前缀(/api/foo→/foo)。
注意一点
/api/*匹配不上/api,建议还是一般使用/api*
反向代理
example.com {
reverse_proxy localhost:8080 # 单个后端
reverse_proxy 127.0.0.1:8080 127.0.0.1:8081 # 多个后端
}
日志
example.com {
log {
output file /var/log/caddy/access.log {
roll_size 100mb
roll_keep 10
roll_keep_for 90d
}
format console # console/json
level INFO # DEBUG/INFO/WARN/ERROR
}
}
常用中间件
1. Header
example.com {
header {
Strict-Transport-Security "max-age=31536000"
X-Frame-Options "DENY"
}
}
2. Rewrite
example.com {
rewrite /old /new
}
3. Redirect (301/302)
example.com {
redir /old /new 301
}
route 用法(显式控制顺序)
example.com {
route {
header Strict-Transport-Security "max-age=31536000"
reverse_proxy localhost:8080
}
}
高级匹配
example.com {
@images {
path *.png *.jpg *.jpeg
}
handle @images {
file_server
root * /var/www/images
}
}
常见完整示例
# 重定向试图使用IP访问的HTTP流量
http://8.8.8.8:80, http://[2001:4860:4860::8888]:80 {
redir https://blog.czuispace.work
}
blog.czuispace.work {
# 自动申请证书,这个是联系邮箱,实际上不重要
tls yourmail@example.com
# 以下两行调换顺序会出事
file_server
root * /var/www/sites/blog/dist
}
blogtemplate.czuispace.work {
tls yourmail@example.com
file_server
root * /var/www/sites/template/dist
}
works.czuispace.work {
tls yourmail@example.com
log {
# 启用访问日志
output file /var/log/caddy/access.log {
# 可选:输出到文件
roll_size 100mb # 滚动大小
roll_keep 10 # 保留文件数
roll_keep_for 90d # 保留天数
}
format console # 格式:json 或 console
}
# 类似alias,如果是handle /dash/*那就会直接拼接,类似location
handle_path /dash* {
file_server
root * /var/www/sites/works/dash
}
handle_path /memorygame* {
file_server
root * /var/www/sites/works/memorygame
}
handle_path /songlist* {
file_server
root * /var/www/sites/works/songlist
}
handle_path /flipcd* {
file_server
root * /var/www/sites/works/flipcd
}
}