免费的 Let's Encrypt 证书
如何用 certbot 在 VPS 上签发并自动续期 HTTPS 证书,包括 80 端口已被占用的情况。
更新于 2026年8月23日
您需要一份证书,否则浏览器会显示“不安全”,表单和支付也完全无法工作。Let's Encrypt 免费签发一份有效期为 90 天的证书,并自动续期。
准备工作
请检查三件事,否则签发会失败:
dig +short example.ru # should return your machine's address
ss -tulpn | grep -E ':80|:443'
- 域名的 A 记录指向控制面板
/hosting/vds/m/<id>页面“概览”标签页中显示的地址; - 端口 80 可从外部访问——Let's Encrypt 用它来验证域名所有权;
- Web 服务器正在运行:Nginx 或 Apache。
如果您使用 Caddy,则无需任何操作——它会自行签发证书。
签发
apt install -y certbot python3-certbot-nginx # Debian, Ubuntu
dnf install -y certbot python3-certbot-nginx # AlmaLinux, CentOS Stream
certbot --nginx -d example.ru -d www.example.ru
对于 Apache,路径相同,只需换成 python3-certbot-apache 和 --apache 参数。Certbot 会自动把证书配置块和 HTTP 到 HTTPS 的跳转写入配置文件。
检查结果:
certbot certificates
curl -I https://example.ru
自动续期
安装包会安装一个系统定时器,续期也由它负责。请确认定时器处于活动状态,并执行一次测试续期:
systemctl list-timers | grep certbot
certbot renew --dry-run
试运行是必须的。它能发现两个月后才会暴露的续期故障——例如您重命名了站点配置,certbot 就不知道把验证文件放到哪里了。
当端口 80 被占用时
如果某个应用正在使用端口 80,而您无法在那里部署 Web 服务器,请使用独立模式:
certbot certonly --standalone --preferred-challenges http -d example.ru
Certbot 会在验证期间启动自己的临时服务器。为此,您必须停止该应用:--pre-hook 和 --post-hook 可以自动完成这一操作。
签发完成后,证书位于 /etc/letsencrypt/live/example.ru/:fullchain.pem 和 privkey.pem。
常见错误
| 现象 | 原因 |
|---|---|
Timeout during connect | 端口 80 被防火墙拦截,或域名指向了另一台机器 |
too many certificates already issued | 您已达到该域名的每周限额——请等待,或用 --staging 调试 |
| 签发后站点仍在使用旧证书 | 您没有重载 Web 服务器:systemctl reload nginx |
| 证书已过期 | 定时器被禁用——请检查 systemctl enable --now certbot.timer |
/etc/letsencrypt目录属于您的数据。机器没有自动备份,因此请将它连同 Web 服务器配置一起纳入您的备份。