Let’s Encrypt SSL 证书申请与自动续签
HTTPS已经成为现代网站的标配,Let’s Encrypt提供免费的SSL证书,配合Certbot工具可以实现证书申请和自动续签,让任何网站都能以零成本启用HTTPS。
一、Let’s Encrypt简介
Let’s Encrypt是由互联网安全研究组(ISRG)运营的免费、自动化、开放的证书颁发机构(CA)。其主要特点:完全免费;证书有效期90天(设计上鼓励自动化续签);通过ACME协议自动化申请和续签;受所有主流浏览器信任。
二、安装Certbot
# CentOS 7/8 yum install -y epel-release yum install -y certbot python3-certbot-nginx # Ubuntu 18.04/20.04 apt install -y certbot python3-certbot-nginx # 或使用snap安装(推荐,版本最新) snap install --classic certbot ln -s /snap/bin/certbot /usr/bin/certbot
三、申请证书(Nginx方式)
# 方式1:Certbot自动配置Nginx(推荐) certbot --nginx -d example.com -d www.example.com # 方式2:仅申请证书,手动配置 certbot certonly --webroot -w /var/www/html -d example.com -d www.example.com # 方式3:DNS验证(适合没有Web服务器的场景,或申请通配符证书) certbot certonly --manual --preferred-challenges dns -d "*.example.com" # 按提示在DNS中添加TXT记录后继续
四、申请通配符证书
通配符证书(Wildcard Certificate)可以保护域名的所有子域,如 *.example.com 可以同时覆盖 www.example.com、api.example.com、admin.example.com 等:
# 通配符证书必须使用DNS验证 certbot certonly --manual --preferred-challenges=dns -d example.com -d "*.example.com" # 根据提示,在DNS中添加 _acme-challenge.example.com 的TXT记录 # 等待DNS生效后(通常1-5分钟)按回车继续
五、Nginx HTTPS配置
server {
listen 443 ssl http2;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# HSTS(告知浏览器始终使用HTTPS)
add_header Strict-Transport-Security "max-age=63072000" always;
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
}
server {
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri; # HTTP强制跳转HTTPS
}
六、配置自动续签
# Certbot安装时会自动创建续签定时任务 # 查看定时任务 systemctl list-timers | grep certbot cat /etc/cron.d/certbot # 或查看crontab # 手动测试续签(不实际续签) certbot renew --dry-run # 如果定时任务不存在,手动创建 echo "0 0,12 * * * root certbot renew --quiet --deploy-hook 'systemctl reload nginx'" >> /etc/crontab # 续签后自动重载Nginx certbot renew --deploy-hook "systemctl reload nginx"
七、证书管理常用命令
certbot certificates # 查看已申请的证书列表 certbot renew # 手动续签所有到期证书 certbot revoke --cert-path /etc/letsencrypt/live/example.com/cert.pem # 吊销证书 certbot delete --cert-name example.com # 删除证书
八、常见问题
- 申请失败提示rate limit:Let’s Encrypt对同一域名每周最多申请5张证书,测试时使用–staging参数使用测试服务器
- 续签失败:检查80端口是否可访问(HTTP-01验证需要);检查.well-known/acme-challenge目录是否可访问
- 证书已过期:手动执行certbot renew,检查自动续签定时任务是否运行正常
九、总结
Let’s Encrypt + Certbot让免费HTTPS的部署变得极其简单,全程不超过5分钟。配置好自动续签后,证书将自动在到期前更新,真正做到”一次配置,永久有效”。建议所有网站都配置HTTPS,不仅保护用户数据安全,也有利于SEO排名。