通过Certbot自动申请更新HTTPS网站的SSL证书
原文地址:通过Certbot自动申请更新HTTPS网站的SSL证书
现在很多云服务运营商免费的HTTPS证书有效期只有3个月,对于个人网站来说,这就很麻烦,现在可以用 Certbot + Crontab 自动申请并定期更新 HTTPS 网站的 SSL 证书,来解决我们这个痛点。
需要云服务器可以看这里:云服务器优惠合集。
1. 安装 Certbot
不同系统安装方式略有不同,这里给你 CentOS / RHEL 和 Debian / Ubuntu 的常用方法。
CentOS / RHEL 7/8/9
# 安装 EPEL
sudo yum install epel-release -y# 安装 Certbot 和 Nginx 插件(如果用 Apache 就换成 python3-certbot-apache)
sudo yum install certbot python3-certbot-nginx -y
Debian / Ubuntu
sudo apt update
sudo apt install certbot python3-certbot-nginx -y
2. 申请 SSL 证书
如果你用 Nginx:
sudo certbot --nginx -d example.com -d www.example.com
-d
参数后面写你的域名(可以多个)- Certbot 会自动修改 Nginx 配置并申请证书
- 申请过程中会让你选择是否重定向 HTTP → HTTPS
注意:这里需要你的nginx的conf文件里面的sercer_name指定对应的域名,如果你配置的是下划线 “_”,会导致该命令运行失败,报下面的错误。
Could not automatically find a matching server block for zhangfeidezhu.com. Set the `server_name` directive to use the Nginx installer.
如果你用 Apache:
sudo certbot --apache -d example.com -d www.example.com
3. 测试证书是否生效
申请完成后,可以在浏览器访问你的域名,查看是否已经是有效的 Let’s Encrypt 证书。
4. 自动更新证书
Let’s Encrypt 证书有效期是 90 天,所以要自动续签。
Certbot 自带定时任务(通常是 /etc/cron.d/certbot
或 systemd 定时器),也可以手动添加 crontab:
sudo crontab -e
加入:
0 3 1 */3 * certbot renew --quiet --post-hook "nginx -s reload"
解释:
0 3 1 */3 *
→ 每隔 3 个月的1号3点执行一次--quiet
→ 静默模式--post-hook "nginx -s reload"
→ 续签后自动重载 Nginx
5. 检查自动续签是否正常
手动测试续签:
sudo certbot renew --dry-run
如果提示 Congratulations, all renewals succeeded,说明没问题。
✅ 这样配置后,你的网站 HTTPS 证书会在到期前自动续签,Nginx 会自动加载新证书,几乎可以做到“一劳永逸”。