使用 Let’s Encrypt 免费为网站申请 HTTPS 证书(完整教程)
📌 本文介绍如何在 Linux(Ubuntu / Debian / CentOS)服务器上,为域名配置免费的 HTTPS 证书,并自动续期。
适用于:
- Nginx / OpenResty
- PHP 网站(如论坛、Flarum)
- 静态站点(Hugo / Vue SPA)
- API 服务
一、准备条件
1️⃣ 必须具备
- 已解析好的域名(A 记录指向服务器 IP)
- 服务器可访问 80 / 443 端口
- root 或 sudo 权限
2️⃣ 检查域名解析
ping forum.happyrock.cloud
或:
nslookup forum.happyrock.cloud
确认指向你的服务器 IP。
二、安装 Certbot(证书申请工具)
Certbot 是 Let’s Encrypt 官方推荐工具:
Certbot
Ubuntu / Debian
sudo apt update
sudo apt install certbot python3-certbot-nginx -y
CentOS / RHEL
sudo yum install epel-release -y
sudo yum install certbot python3-certbot-nginx -y
三、申请 HTTPS 证书(自动模式)
方式一:Nginx 自动配置(推荐)
sudo certbot --nginx
执行后会:
- 自动扫描 Nginx 域名
- 选择要启用 HTTPS 的站点
- 自动修改配置文件
- 自动申请证书
方式二:指定域名申请(更可控)
sudo certbot --nginx -d forum.happyrock.cloud
四、手动模式(适用于 OpenResty / 高定制)
如果你用 OpenResty(你当前环境就是),推荐用 standalone 或 webroot:
方案 A:webroot 模式(推荐生产)
sudo certbot certonly --webroot \
-w /var/www/forum/public \
-d forum.happyrock.cloud
方案 B:standalone 模式(临时占用80端口)
sudo systemctl stop openresty
sudo certbot certonly --standalone \
-d forum.happyrock.cloud
sudo systemctl start openresty
五、证书文件位置
申请成功后会生成:
/etc/letsencrypt/live/forum.happyrock.cloud/
包含:
- fullchain.pem(证书链)
- privkey.pem(私钥)
六、Nginx 配置 HTTPS
修改 server 块:
server {
listen 443 ssl http2;
server_name forum.happyrock.cloud;
ssl_certificate /etc/letsencrypt/live/forum.happyrock.cloud/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/forum.happyrock.cloud/privkey.pem;
root /var/www/forum/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include fastcgi.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
}
七、HTTP 自动跳转 HTTPS(强烈建议)
新增 80 端口:
server {
listen 80;
server_name forum.happyrock.cloud;
return 301 https://$host$request_uri;
}
八、自动续期(关键步骤)
Let’s Encrypt 证书 90 天过期,但可以自动续期。
1️⃣ 测试续期
sudo certbot renew --dry-run
2️⃣ 添加定时任务(系统已默认)
查看:
systemctl list-timers | grep certbot
3️⃣ 手动 cron(保险方案)
crontab -e
添加:
0 3 * * * certbot renew --quiet
九、常见问题排查
❌ 1. 80 端口被占用
lsof -i :80
解决:
- 停止 nginx/openresty 临时服务
- 或使用 webroot 模式
❌ 2. 域名验证失败
检查:
- DNS 是否生效
- 防火墙是否开放 80
- Nginx 是否正确响应 /.well-known/
❌ 3. 证书申请成功但浏览器不生效
检查:
- 是否重启 Nginx/OpenResty
- 是否配置了正确 server_name
- 是否有多个 443 冲突配置
十、最佳实践总结(很重要)
✔ 优先用 webroot 模式 ✔ 统一 443 配置(避免冲突) ✔ PHP 用 socket,不用 127.0.0.1:9000 ✔ 开启 HTTP → HTTPS 强制跳转 ✔ certbot 自动续期必须验证
🚀 如果你下一步想升级
可以继续做这些:
- 🔐 OpenResty + WAF 防护 HTTPS 体系
- 🚀 多域名统一 SSL 管理
- 🧠 自动部署 HTTPS(CI/CD)
- 🔥 防扫描 + 防爆破 + 限流
👉 “做 HTTPS + 安全生产架构升级”,升级成一套企业级部署模板。