什么是Caddy

Caddy服务器是一个开源的,使用 Golang 编写,支持 HTTP/2 的 Web 服务端。它使用Golang 标准库提供HTTP 功能。 Caddy 一个显著的特性是默认启用HTTPS。它是第一个无需额外配置即可提供HTTPS 特性的Web 服务器。

安装Caddy v2

官方文档:https://caddyserver.com/docs/install

sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
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
caddy version
# v2.4.1 h1:kAJ0JB5Xk5gPdTH/27S5cyoMGqD5lBAe9yZ8zTjVJa0=

# 返回以上内容表示安装成功

使用Caddy

官方文档:https://caddyserver.com/docs/getting-started

caddy常用命令

caddy run
# 以守护进程方式启动

caddy starat
# 在后台运行

caddy stop
# 停止运行

caddy reload
# 重新加载配置文件

caddy help
# 返回帮助内容

通过api配置Caddy

新建caddy.json文件,写入以下内容保存

{
    "apps": {
        "http": {
            "servers": {
                "example": {
                    "listen": [":2015"],
                    "routes": [
                        {
                            "handle": [{
                                "handler": "static_response",
                                "body": "Hello, world!"
                            }]
                        }
                    ]
                }
            }
        }
    }
}
curl localhost:2019/load -X POST -H "Content-Type: application/json" -d @caddy.json
# 加载配置

curl localhost:2019/config
# 查看配置

curl localhost:2015
# Hello, world!

通过Caddyfile配置Caddy

新建Caddyfile文件,写入以下内容保存

:2015

respond "Hello, world!2"
caddy stop
# 停止caddy

caddy adapt --config Caddyfile
# 使用配置适配器
# 将caddyfile转换成json并输出内容

caddy start --config Caddyfile --adapter caddyfile
# --config Caddyfile文件
# --adapter caddyfile表示加载Caddyfile配置

# OR

caddy start --config caddy.json
# 加载json格式配置


curl localhost:2015
# Hello, world!2

总结

  1. Caddy一共有两种配置格式,分别是JSON和Caddyfile,可以通过adapt命令将JSON格式配置转换成Caddyfile格式。
  2. Caddy有两种加载方式分别是通过API在线加载和通过启动参数加载。

官方文档:

https://caddyserver.com/docs/

阅读更多:

https://mritd.com/2021/01/07/lets-start-using-caddy2/

https://mritd.com/2021/06/30/understand-caddyfile-syntax/