2025 Leo. All rights reserved. Powered by saicaca/fuwari (MIT License).
522 字
3 分钟
HTTPS证书配置指南
本文涉及操作以 ContOS7 为例。
1. 安装 certbot 及 Nginx 插件
首先安装必要的软件包:
sudo yum install -y epel-releasesudo yum install -y certbot python2-certbot-nginx2. 确保域名已解析到服务器
在申请证书前,请确保:
- 域名 DNS 已正确解析到你的服务器 IP
- Nginx 已启动并监听 80 端口
- 防火墙已开放 80 和 443 端口
# 将http和https端口加入防火墙白名单sudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --permanent --add-service=https# 重新加载防火墙规则sudo firewall-cmd --reload3. 使用 certbot 申请并配置证书
- 单个域名自动配置
sudo certbot --nginx -d yourdomain.com- 多域名证书自动配置
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com- 交互式配置
sudo certbot --nginx
# 然后按提示选择域名和配置选项。4. certbot 自动完成的操作
certbot 会自动完成以下操作:
- 验证域名所有权。
- 申请 Let’s Encrypt 证书。
- 自动修改 Nginx 配置文件,添加 SSL 配置。
- 设置 HTTP 到 HTTPS 的重定向。
- 重新加载 Nginx 配置。
5. 验证证书配置
- 检查配置:
# 检查 Nginx 配置sudo nginx -t
# 查看证书信息sudo certbot certificates- 浏览器验证:
在浏览器访问 https://yourdomain.com 验证证书是否生效。
6. 自动续期
certbot 安装后会自动配置续期任务,可以进行测试:
# 测试自动续期(不会真正续期)sudo certbot renew --dry-run
# 手动续期(如需要)sudo certbot renew检查自动续期任务:
# 检查 cron 任务sudo crontab -l
# 检查 certbot timer 状态sudo systemctl status certbot.timer
# 查看 systemd timersudo systemctl list-timers | grep certbot7. 自动生成的 Nginx 配置示例
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; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
# 你的其他配置... location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }}
# HTTP 重定向到 HTTPSserver { listen 80; server_name yourdomain.com; return 301 https://$server_name$request_uri;}8. 注意事项
- Let’s Encrypt 证书有效期为 90 天,注意配置自动续期或者到期手动续证书。
- 确保服务器时间准确,避免证书验证失败。
- 建议定期备份证书文件到安全位置。