VPSVane 风向标

教程 / 网络与线路

SSL 证书自动化

证书到期才发现,站点已经打不开了

中级 45 分钟 6 节 速查

做完你能

把申请、续期和线上复核做成自动化流程

  • Certbot
  • DNS-01
  • 自动续期

站点要上 HTTPS,又不想每年为一张 DV 证书付钱,Let’s Encrypt 就够用。代价是有效期只有 90 天,续期必须真的跑起来,而且不能只看脚本退出码就放心。判断标准很直接:能自动化续期、能从外部验证线上证书,就自己签;否则老老实实买长期证书。

免费证书够用在哪

DV 证书只验证域名所有权,几分钟签发,个人站、博客、API、内部服务都合适。OV 和 EV 要人工核验组织信息,价格高、周期长,一般只有对外品牌站才需要。

现阶段优先用 Let’s Encrypt。ZeroSSL 也能用,免费版有数量限制。

certbot:先备份配置再动手

Nginx 插件最省事,它会自己改配置加证书。正因为会改配置,跑之前先备份、先测语法。

cp -a /etc/nginx /root/nginx.bak
nginx -t
apt install certbot python3-certbot-nginx -y
certbot --nginx -d yourdomain.com -d www.yourdomain.com

前提是 server_name、A/AAAA 记录和 80 端口三者一致。Standalone 模式会临时占用 80,有服务在跑就会抢端口,宁可改用 webroot。

certbot certonly --webroot -w /var/www/html -d yourdomain.com

acme.sh:把证书装到稳定路径

acme.sh 是纯 Shell 实现,不依赖 Python。它把证书放在自己的目录里,别让 Nginx 直接指过去,升级或重装会断。

git clone https://github.com/acmesh-official/acme.sh.git
cd acme.sh && ./acme.sh --install -m your@email.com

申请后单独做一步安装,把文件复制到 /etc/nginx/ssl 并挂上重载命令。

~/.acme.sh/acme.sh --issue -d yourdomain.com --webroot /var/www/html
~/.acme.sh/acme.sh --install-cert -d yourdomain.com \
  --fullchain-file /etc/nginx/ssl/fullchain.cer \
  --key-file /etc/nginx/ssl/yourdomain.com.key \
  --reloadcmd "systemctl reload nginx"

—install-cert 里的 reloadcmd 会跟着续期一起执行,这一步才是自动化的关键。

通配符:只能走 DNS-01

*.yourdomain.com 覆盖所有二级子域,验证方式必须是 DNS-01,HTTP-01 做不到。certbot 配 Cloudflare 插件,token 放独立文件并限权。

mkdir -p /root/.secrets
printf 'dns_cloudflare_api_token = 你的Token\n' > /root/.secrets/cloudflare.ini
chmod 600 /root/.secrets/cloudflare.ini
certbot certonly --dns-cloudflare \
  --dns-cloudflare-credentials /root/.secrets/cloudflare.ini \
  -d yourdomain.com -d "*.yourdomain.com"

token 只给解析编辑权限,别用全局密钥。acme.sh 对应的是 —dns dns_cf,用完 unset 环境变量。

续期:别看退出码,看线上证书

Certbot 的 renew 在没有证书需要更新时也返回成功,所以退出码证明不了线上已经换过证书。查 timer 状态,再跑一次演练。

systemctl list-timers | grep certbot
certbot renew --dry-run

重载要绑在「部署成功」之后,用 deploy hook,而不是 post-hook,避免验证失败时也把重载算成续期成功。

install -d -m 0755 /etc/letsencrypt/renewal-hooks/deploy
printf '#!/bin/sh\nnginx -t && systemctl reload nginx\n' \
  > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx
chmod 0755 /etc/letsencrypt/renewal-hooks/deploy/reload-nginx

本地文件的修改时间不作数,从外部读线上证书的到期时间。

echo | openssl s_client -connect yourdomain.com:443 -servername yourdomain.com 2>/dev/null \
  | openssl x509 -noout -dates -subject

notAfter 应该是 90 天内的新日期,subject 里的域名对得上。再用浏览器或 SSL Labs 复核一次链完整性和 TLS 版本,两项都过才算收工。

常见坑

  • 只开了 Nginx 插件没确认 80 端口可达,签发一直超时。
  • 证书装好了但没配 reloadcmd,续期成功而服务还用着旧证书。
  • 通配符用 HTTP-01,怎么试都签不下来。
  • Cloudflare 开了橙云还走 HTTP-01,验证请求被 CDN 拦在半路。