在 CentOS 系统中使用 Certbot 自动申请和续期 SSL 证书的步骤如下,以 Nginx 为例(Apache 步骤类似,只需替换对应插件):
一、安装 Certbot 及依赖
CentOS 系统需先启用 EPEL 仓库(提供 Certbot 包),再安装相关组件:
# 1. 安装 EPEL 仓库(CentOS 7/8 通用)
sudo yum install -y epel-release
# 2. 安装 Certbot 及 Nginx 插件
# CentOS 7
sudo yum install -y certbot python2-certbot-nginx
# CentOS 8(Python 3 版本)
sudo dnf install -y certbot python3-certbot-nginx
二、申请证书并自动配置 Nginx
根据证书类型(单域名/通配符)选择对应命令:
1. 单域名/多域名证书(HTTP 验证,简单快捷)
适用于普通域名(如 example.com
、www.example.com
),通过 HTTP 方式验证域名所有权:
sudo certbot --nginx -d example.com -d www.example.com
- 执行后会自动完成:
- 申请 Let’s Encrypt 证书
- 修改 Nginx 配置(添加 SSL 配置,替换原有证书路径)
- 自动启用 HTTPS 并跳转(HTTP → HTTPS)
2. 通配符证书(DNS 验证,支持 *.example.com
)
适用于需要覆盖所有子域名的场景(如 a.example.com
、b.example.com
),需通过 DNS TXT 记录验证:
sudo certbot --nginx -d example.com -d *.example.com
- 执行后会提示:
- 生成一条 DNS TXT 记录(格式如
_acme-challenge.example.com
对应一串随机值) - 登录你的域名解析平台(如阿里云、Cloudflare 等),添加该 TXT 记录
- 等待 DNS 生效(约 5-10 分钟,可通过
nslookup -type=TXT _acme-challenge.example.com
验证) - 按回车继续,完成证书申请和配置
- 生成一条 DNS TXT 记录(格式如
三、验证证书安装
# 查看已安装的证书信息
sudo certbot certificates
输出会显示证书路径(通常在 /etc/letsencrypt/live/example.com/
)、有效期等信息。
四、自动续期配置
Let’s Encrypt 证书有效期为 90 天,Certbot 会自动创建定时任务续期:
# 查看自动续期任务(CentOS 7 用 cron,CentOS 8 用 systemd-timer)
# CentOS 7
sudo crontab -l | grep certbot
# CentOS 8
sudo systemctl list-timers | grep certbot
手动测试续期(推荐首次使用时验证):
# 模拟续期(不实际修改证书)
sudo certbot renew --dry-run
# 若测试通过,实际续期命令(正常情况下无需手动执行,定时任务会自动运行)
sudo certbot renew
# 续期后重载 Nginx 使新证书生效(定时任务会自动处理)
sudo systemctl reload nginx
五、关键说明
自动替换 Nginx 配置:
使用--nginx
插件时,Certbot 会自动修改 Nginx 配置文件(通常在/etc/nginx/conf.d/
或/etc/nginx/sites-available/
),更新ssl_certificate
和ssl_certificate_key
路径,覆盖原有证书配置。卸载证书:
若需删除证书并恢复配置:sudo certbot delete --cert-name example.com
防火墙配置:
确保 443 端口(HTTPS)已开放:# CentOS 7 sudo firewall-cmd --add-service=https --permanent sudo firewall-cmd --reload # CentOS 8 sudo firewall-cmd --add-service=https --permanent sudo firewall-cmd --reload
通过以上步骤,即可在 CentOS 系统中使用 Certbot 免费、自动地管理 SSL 证书,包括申请、续期和配置 Nginx。