Nginx 从 0 到 1 配置 HTTPS:实战指南(含 Certbot 自动签发)
为网站配置 HTTPS 是保障用户数据传输安全、提升用户信任感的重要手段。本文将手把手带你完成 Nginx HTTPS 配置,包括域名准备、证书申请、Nginx 配置及自动续期等关键步骤。
为网站配置 HTTPS 是保障用户数据传输安全、提升用户信任感的重要手段。本文将手把手带你完成 Nginx HTTPS 配置,包括域名准备、证书申请、Nginx 配置及自动续期等关键步骤。
🧱 一、前置准备
✅ 1. 一台具备公网 IP 的服务器
确保服务器具备:
- 可访问外网;
- 端口
80和443没有被防火墙或云安全组屏蔽; - 已安装 Linux 操作系统,如 CentOS、Ubuntu。
✅ 2. 一个备案并可控的域名
例如:test.example.com,并完成如下配置:
- 在域名服务商控制台设置
A 记录指向服务器公网 IP; - 等待解析生效,可使用以下命令确认:
ping test.example.com
dig +short test.example.com
🛠️ 二、安装 Nginx(以 CentOS 为例)
sudo yum install epel-release -y
sudo yum install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx
🔧 三、配置 Nginx 用于 HTTPS 验证
在正式申请 HTTPS 证书前,Let’s Encrypt 会向你网站的 .well-known/acme-challenge/ 路径发送请求进行验证。因此你需要提前配置 Nginx 正确响应该路径。
✅ 配置验证路径
- 创建验证目录:
sudo mkdir -p /var/www/letsencrypt/.well-known/acme-challenge
sudo chmod -R 755 /var/www/letsencrypt
- 在
/etc/nginx/conf.d/test.example.com.conf配置文件中添加:
server {
listen 80;
server_name test.example.com;
# 验证挑战路径,必须提前配置好
location ^~ /.well-known/acme-challenge/ {
root /var/www/letsencrypt;
try_files $uri =404;
}
# 其他路径可暂时返回 404
location / {
return 404;
}
}
- 重载 Nginx 配置:
sudo nginx -t
sudo systemctl reload nginx
- 测试是否能访问:
echo hello > /var/www/letsencrypt/.well-known/acme-challenge/test-token
curl http://test.example.com/.well-known/acme-challenge/test-token
输出 hello 表示验证路径配置成功。
🔐 四、安装 Certbot 并申请 HTTPS 证书
✅ 安装 Certbot 工具(以 CentOS 为例):
sudo yum install certbot python3-certbot-nginx -y
✅ 使用 webroot 模式申请证书(不会修改 Nginx 配置):
sudo certbot certonly --webroot -w /var/www/letsencrypt -d test.example.com
执行成功后,证书将保存在:
/etc/letsencrypt/live/test.example.com/
📦 五、配置 Nginx 启用 HTTPS
在 /etc/nginx/conf.d/test.example.com.conf 中补充 HTTPS server 块:
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name test.example.com;
return 301 https://$host$request_uri;
}
# HTTPS 正式服务
server {
listen 443 ssl http2;
server_name test.example.com;
ssl_certificate /etc/letsencrypt/live/test.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/test.example.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:8082;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
重启 Nginx:
sudo nginx -t
sudo systemctl reload nginx
此时,你可以通过浏览器访问 https://test.example.com/,验证 HTTPS 是否生效。
🔁 六、设置自动续期
Let’s Encrypt 的证书有效期为 90 天,建议配置自动续期。
Certbot 安装时通常已自动添加续期任务(通过 /etc/cron.d 或 systemd)。你可以手动测试:
sudo certbot renew --dry-run
如需手动配置,可加入 crontab:
0 3 * * * /usr/bin/certbot renew --quiet
📎 七、小结
通过本文步骤,你完成了以下关键任务:
- 配置了 Nginx 支持 HTTPS 所需的
.well-known/acme-challenge/路径; - 成功使用 Certbot + Let’s Encrypt 签发免费证书;
- 在 Nginx 中配置了自动跳转、证书加载与后端反向代理;
- 添加了自动续期机制。
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)