Nginx + Certbot 自动HTTPS证书与反向代理完整教程

本文将手把手教你如何为域名(如 artalk.cdd9527.cn)配置 HTTPS,并通过 Nginx 实现反向代理,同时支持证书自动续期。


一、准备条件

在开始之前,请确保满足以下条件:

  • 已拥有域名(如 artalk.cdd9527.cn

  • 域名已解析到服务器 IP

  • 服务器已安装 Nginx

  • 已开放端口:

    • 80(HTTP)
    • 443(HTTPS)

二、安装 Certbot

Ubuntu / Debian

1
2
apt update
apt install certbot python3-certbot-nginx -y

三、申请 HTTPS 证书

执行以下命令:

1
certbot --nginx -d artalk.cdd9527.cn

过程中会提示:

1. 输入邮箱

用于证书续期提醒

2. 是否同意协议

输入:

1
Y

3. 是否接收邮件

建议:

1
N

四、成功标志

如果看到:

1
Congratulations! Your certificate and chain have been saved

说明证书申请成功 ✅


五、Nginx 标准配置(推荐)

1️⃣ HTTP 自动跳转 HTTPS

1
2
3
4
5
6
server {
listen 80;
server_name artalk.cdd9527.cn;

return 301 https://$host$request_uri;
}

2️⃣ HTTPS + 反向代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server {
listen 443 ssl;
server_name artalk.cdd9527.cn;

ssl_certificate /etc/letsencrypt/live/artalk.cdd9527.cn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/artalk.cdd9527.cn/privkey.pem;

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;

location / {
proxy_pass http://127.0.0.1:5006;

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

六、访问效果

现在访问:

1
https://artalk.cdd9527.cn

实际访问路径:

1
用户 → Nginx(443) → 本地服务(5006)

👉 不再暴露端口,更安全


七、自动续期

Certbot 会自动添加定时任务

手动测试:

1
certbot renew --dry-run

八、常见问题

1️⃣ 提示 nginx 插件不存在

1
The requested nginx plugin does not appear to be installed

解决:

1
apt install python3-certbot-nginx -y

2️⃣ 验证失败(80端口问题)

原因:

  • 80端口未开放
  • 被防火墙拦截

解决:

1
2
ufw allow 80
ufw allow 443

3️⃣ 域名解析错误

检查:

1
ping artalk.cdd9527.cn

4️⃣ Nginx 配置错误

检查:

1
nginx -t

九、进阶建议

推荐优化:

  • 不暴露业务端口(如 5006)
  • 所有服务统一走 Nginx
  • 多域名统一管理

十、总结

完整流程如下:

  1. 安装 Certbot
  2. 申请证书
  3. 配置 Nginx
  4. 开启 HTTPS
  5. 自动续期

👉 核心原则:

  • 80端口:用于跳转 + 验证
  • 443端口:用于正式服务

延伸阅读