Caddy使用说明

Caddy相较Nginx更为简单,做服务器代理太方便了,尤其是HTTPS证书获取。这里记录下常用操作。

安装

推荐走包管理器安装,比如Mac下

1
brew install caddy

CentOS7如下

1
2
3
yum install yum-plugin-copr
yum copr enable @caddy/caddy
yum install caddy

Ubuntu如下

1
2
3
4
5
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

其它OS安装见 https://caddyserver.com/docs/install#install

常用命令

1
2
3
4
5
6
7
8
# 启动服务
caddy start --config ./Caddyfile

# 格式化
caddy fmt --overwrite

# 停止服务
caddy stop

例子

反向代理内网服务

1
2
3
4
5
6
127.0.0.1:3001 {
route /xyz* {
uri strip_prefix /xyz
reverse_proxy 127.0.0.1:8080
}
}

反向代理外部服务

1
2
3
4
5
example.com {
reverse_proxy /v1/chat/completions https://api.openai.com {
header_up Host {upstream_hostport}
}
}

静态资源

1
2
3
4
1991421.cn {
root * /var/www/blog/public
file_server
}

写在最后

更多资料推荐查看官网 https://caddyserver.com/docs/caddyfile