以下是详细的操作步骤,涵盖环境准备、证书申请、配置优化及自动续期等关键环节:
sudo apt update && sudo apt upgrade -ysudo apt install nginx完成)Certbot是自动化获取和管理SSL证书的工具,其与Nginx的集成插件可简化配置流程。执行以下命令安装:
sudo apt install certbot python3-certbot-nginx -y
安装完成后,通过certbot --version验证是否安装成功。
使用Certbot的--nginx插件自动获取证书,并指定域名(支持多域名,如-d yourdomain.com -d www.yourdomain.com):
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
执行过程中,Certbot会引导完成以下步骤:
Certbot会自动修改Nginx配置文件(通常位于/etc/nginx/sites-available/或/etc/nginx/conf.d/),启用HTTPS并配置SSL参数。检查配置文件是否包含以下关键内容:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri; # 强制跳转HTTPS
}
server {
listen 443 ssl http2; # 启用HTTP/2提升性能
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem; # 证书链文件
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem; # 私钥文件
include /etc/letsencrypt/options-ssl-nginx.conf; # 默认SSL配置(协议、加密套件等)
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # DH参数(增强安全性)
root /var/www/html;
index index.html index.htm;
}
确认配置无误后,测试Nginx语法并重启服务:
sudo nginx -t # 测试配置文件语法
sudo systemctl restart nginx # 重启Nginx
通过浏览器访问https://yourdomain.com,若地址栏显示安全锁图标,则说明证书生效。
Let’s Encrypt证书有效期为90天,需定期续期以避免服务中断。Certbot默认会创建systemd定时器(certbot.timer),每天自动检查证书有效期,并在到期前续期。
sudo systemctl list-timers | grep certbot(若显示“active”则表示已启用);sudo certbot renew --dry-run(无报错则表示自动续期功能正常)。sudo ufw allow 'Nginx Full';/etc/nginx/options-ssl-nginx.conf文件;journalctl -u certbot查看详细日志排查问题。