Nginx 免费SSL与自动续期管理
2025年 Nginx 免费 SSL 自动续期管理方案
在 2025 年,使用 Let's Encrypt 提供的免费 SSL 证书结合 Certbot 工具,是 Nginx 服务器实现 HTTPS 加密和自动续期的标准方案。Let's Encrypt 证书有效期为 90 天,Certbot 会自动处理续期,避免手动干预。以下基于最新指南,提供 Ubuntu/Debian 系统下的完整步骤(适用于 Nginx 已安装的环境)。整个过程通常只需几分钟。
前提条件
- 服务器:Ubuntu 20.04+ 或 Debian 11+。
- Nginx 已安装并配置好域名指向(A 记录)。
- 域名已解析到服务器 IP。
- root 或 sudo 权限。
步骤 1: 安装 Certbot 和 Nginx 插件
Certbot 是 Let's Encrypt 的官方客户端,Nginx 插件会自动配置服务器块。
# 更新系统
sudo apt update
# 安装 Certbot 和 Nginx 插件
sudo apt install certbot python3-certbot-nginx
如果使用 Snap 安装(推荐用于最新版本):
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
步骤 2: 获取 SSL 证书
运行 Certbot 的 Nginx 向导,它会自动验证域名、生成证书并修改 Nginx 配置(添加 SSL 块、重定向 HTTP 到 HTTPS)。
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
- 输入邮箱地址(用于续期通知)。
- 同意条款。
- 选择要保护的域名。
- 选择是否重定向 HTTP 到 HTTPS(推荐 Yes)。
证书文件将保存在 /etc/letsencrypt/live/yourdomain.com/,包括 fullchain.pem(证书链)和 privkey.pem(私钥)。
测试续期(干运行模式):
sudo certbot renew --dry-run
步骤 3: 配置自动续期
Certbot 安装后会自动创建 systemd timer 或 cron 任务,每日检查证书(推荐每 12 小时运行一次)。如果未自动配置,手动添加 cron 任务。
编辑 cron 文件:
sudo nano /etc/cron.d/certbot
添加以下内容(每 12 小时运行一次,安静模式):
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
0 */12 * * * root certbot -q renew --nginx
保存后,启用 cron 服务(如果未运行):
sudo systemctl enable cron
sudo systemctl start cron
--nginx参数确保续期后自动重载 Nginx 配置。- 如果使用 webroot 方法(手动配置),续期命令为
sudo certbot renew --webroot -w /var/www/html。
步骤 4: 验证和监控
- 检查证书状态:
sudo certbot certificates。 - 查看 Nginx 配置:
sudo nginx -t。 - 监控日志:
/var/log/letsencrypt/letsencrypt.log。 - 续期阈值:Certbot 在证书到期前 30 天内自动续期。
常见问题与优化
- 端口 80 阻塞:确保防火墙允许 80/443 端口(
sudo ufw allow 'Nginx Full')。 - 多域名:在步骤 2 中添加多个
-d参数。 - HSTS 支持:在 Nginx 配置中添加
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";以增强安全。 - 2025 更新:Let's Encrypt 仍使用 ACME v2 协议,无重大变更;Certbot 版本建议保持最新(
sudo apt update && sudo apt upgrade certbot)。
| 方案组件 | 工具/命令 | 频率 |
|---|---|---|
| 证书获取 | certbot --nginx |
一次性 |
| 手动续期 | certbot renew --nginx |
按需 |
| 自动续期 | cron 任务 | 每 12 小时 |
| 测试续期 | certbot renew --dry-run |
每月 |
此方案免费、可靠,已在生产环境中广泛使用。 如需特定发行版调整,参考官方文档。