使用 Let's Encrypt 为 Nginx 配置 HTTPS 可以通过 Certbot 工具快速实现。以下是详细步骤:
sudo systemctl status nginx
)# Ubuntu/Debian
sudo apt update
sudo apt install certbot python3-certbot-nginx
# CentOS/RHEL
sudo yum install epel-release
sudo yum install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Certbot 会自动: 1. 验证域名所有权 2. 获取证书 3. 修改 Nginx 配置启用 HTTPS 4. 设置自动续期
# 仅获取证书(不修改配置)
sudo certbot certonly --nginx -d yourdomain.com
# 手动修改 Nginx 配置
sudo vim /etc/nginx/sites-available/yourdomain.conf
添加以下配置:
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
# 其他配置...
}
在 Nginx 配置中添加 301 重定向:
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
sudo nginx -t # 测试配置
sudo systemctl reload nginx
Let's Encrypt 证书有效期为 90 天,设置自动续期:
# 测试续期命令
sudo certbot renew --dry-run
# 添加定时任务(每月执行)
sudo crontab -e
添加以下行:
0 0 1 * * /usr/bin/certbot renew --quiet
访问 https://yourdomain.com
,浏览器应显示绿色锁标志。可通过 SSL Labs 测试安全性。
证书获取失败
sudo lsof -i :80
)Nginx 配置错误
nginx -t
检查语法yourdomain.com
需替换为实际域名)混合内容警告
https://
链接通过以上步骤,你的 Nginx 将获得免费的 Let's Encrypt HTTPS 证书,并自动维护续期。