申请 Let's Encrypt 公网 IP 证书并部署至 Caddy

Let’s Encrypt 支持通过 shortlived(短期证书,有效期 6 天)配置文件为公网 IP 申请可信的 SSL 证书。本文提供两种实现方案:Caddy 原生自动托管(首选)acme.sh 独立申请 + Caddy 部署(备选)


方案一:高版本 Caddy 原生自动托管(极简推荐)

原生自动托管要求 Caddy 版本 >= v2.10.0。由于系统默认 apt 源的 Caddy 版本通常较老,必须先配置官方源进行安装或升级。

1. 安装/升级最新版 Caddy (Debian/Ubuntu)

执行以下命令配置 Caddy 官方源并安装最新版本(包含必要依赖包的补全):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 1. 升级系统软件源并安装底层的信任库与基础联络工具
sudo apt update
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl gnupg ca-certificates

# 2. 导入官方仓库 GPG key
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
| sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg

# 3. 添加官方 Debian/Ubuntu 软件源
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
| sudo tee /etc/apt/sources.list.d/caddy-stable.list

# 4. 更新源并安装/更新 Caddy
sudo apt update
sudo apt install -y caddy

安装完成后,可通过 caddy version 确认版本号 >= v2.10.0。

2. 编写 Caddyfile

编辑 /etc/caddy/Caddyfile,在全局配置块中加入 profile shortlived

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
# 全局配置:指定 ACME 签发器并启用短期证书 Profile
certissuer acme {
profile shortlived
}
}

# 你的公网 IPv4
1.2.3.4 {
reverse_proxy localhost:15001
}

# 你的公网 IPv6(必须加中括号)
[2001:db8::1] {
reverse_proxy localhost:15001
}

3. 生效配置

1
2
3
4
5
# 验证配置
caddy validate --config /etc/caddy/Caddyfile

# 重载 Caddy
systemctl reload caddy

Caddy 会自动通过 HTTP-01 或 TLS-ALPN-01 验证并托管该 IP 证书,每隔约 3 天自动无缝续期,完全无需人工干预。


方案二:使用 acme.sh 独立申请并部署(备选)

若因特殊原因无法升级 Caddy,或需要将证书文件落地供其他服务使用,可使用 acme.sh 手动申请。

1. 环境准备

1
2
3
4
5
6
# 补全基础网络依赖,再行取用 acme.sh 脚本
sudo apt update && sudo apt install -y curl ca-certificates

curl https://get.acme.sh | sh
source ~/.bashrc
acme.sh --register-account --server letsencrypt

2. 申请 IP 证书 (以 1.2.3.4 为例)

由于 Let’s Encrypt 默认 Profile 不支持 IP,必须显式指定 shortlived 配置文件。

  • 方案 A:HTTP-01 验证(走 80 端口,需临时停用 Caddy)

    1
    2
    3
    4
    5
    6
    7
    systemctl stop caddy
    acme.sh --issue -d 1.2.3.4 \
    --standalone \
    --server letsencrypt \
    --certificate-profile shortlived \
    --days 6 --ecc
    systemctl start caddy
  • 方案 B:TLS-ALPN-01 验证(走 443 端口,当 80 端口被封时使用)

    1
    2
    3
    4
    5
    6
    7
    systemctl stop caddy
    acme.sh --issue -d 1.2.3.4 \
    --alpn \
    --server letsencrypt \
    --certificate-profile shortlived \
    --days 6 --ecc
    systemctl start caddy

3. 安装证书并修正权限

将证书安装到固定目录,并授予 caddy 用户读取权限(否则 Caddy 启动会报 permission denied):

1
2
3
4
5
6
7
8
9
10
# 安装证书
acme.sh --install-cert -d 1.2.3.4 --ecc \
--key-file /etc/ssl/ip.key \
--fullchain-file /etc/ssl/ip.fullchain.crt \
--reloadcmd "systemctl reload caddy"

# 修正权限
chown root:caddy /etc/ssl/ip.key /etc/ssl/ip.fullchain.crt
chmod 640 /etc/ssl/ip.key
chmod 644 /etc/ssl/ip.fullchain.crt

4. 配置 Caddy 加载本地证书

编辑 /etc/caddy/Caddyfile 手动引入证书:

1
2
3
4
https://1.2.3.4 {
tls /etc/ssl/ip.fullchain.crt /etc/ssl/ip.key
reverse_proxy localhost:15001
}

最后执行 systemctl reload caddy 即可。