×

使用 Nginx 部署反向代理并使用模块自动配置和续期 SSL (Certbot)

hqy hqy 发表于2026-03-24 21:30:15 浏览7 评论0

抢沙发发表评论

概述在 Debian 13 通过 Nginx 作为反向代理并结合 Certbot 自动化部署 Let’s Encrypt 证书的完整流程。涵盖安装 Nginx、验证 SSL 模块、安装 Certbot、配置基础代理(转发到内网端口、传递真实 IP、支持 WebSocket),使用 nginx 插件自动获取证书并修改配置实现 HTTPS 与 80 的 HTTP 重定向,证书有效期为 90 天,利用 certbot.timer 自动续期并提供 dry-run 测试。

安装 Nginx,配置反向代理,并使用 Certbot 自动化部署 Let's Encrypt 证书

我使用的是debian13

1. 安装 Nginx

首先更新软件包列表并安装 Nginx。

shellscript
apt update && apt install nginx

验证模块支持: Debian 官方仓库的 Nginx 默认编译了 SSL 模块。可以通过以下命令确认:

shellscript
nginx -V 2>&1 | grep --color -o with-http_ssl_module

执行结果如下

shellscript
root# nginx -V 2>&1 | grep --color -o with-http_ssl_modulewith-http_ssl_module


2. 安装 Certbot

shellscript
apt install certbot python3-certbot-nginx -y


3. 配置 Nginx 反向代理

在申请 SSL 证书之前,先创建一个基础的 HTTP 配置文件。

sudo vim /etc/nginx/conf.d/test.ceshi.com.conf

nginx
server {    listen 80;    server_name test.ceshi.com;    client_max_body_size 1024m;    location / {        proxy_pass http://127.0.0.1:5000;                # 传递真实的客户端 IP 和 协议        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;        # 支持 WebSocket (可选,对某些现代 Web 应用很重要)        proxy_http_version 1.1;        proxy_set_header Upgrade $http_upgrade;        proxy_set_header Connection "upgrade";    }}

检查配置并重启服务:

shellscript
nginx -tsystemctl restart nginx

此时请确保域名 test.ceshi.com 已解析到服务器 IP,且 80 端口已开放。


4. 自动申请 SSL 证书

使用 Certbot 的 Nginx 插件,它会自动验证域名、获取证书并修改 Nginx 配置。

shellscript
certbot --nginx -d test.ceshi.com


5. 最终配置解析

执行完 Certbot 后,配置文件 /etc/nginx/conf.d/test.ceshi.com.conf 会被自动修改。其核心逻辑如下:

  • HTTPS (443) 模块: Certbot 自动插入了 ssl_certificate 相关路径和安全参数。

  • HTTP 重定向: 增加了一个专门处理 80 端口的 server 块,将所有请求通过 301 状态码强制跳转至 HTTPS,确保通信安全。

6. 维护与自动续期

Let's Encrypt 证书有效期为 90 天。Debian 13 在安装 certbot 后会自动创建定时任务。

检查续期服务是否正常:

shellscript
systemctl status certbot.timer
SnowShot_2026-01-04_15-02-17.webp

测试手动续期(模拟):

shellscript
certbot renew --dry-run


打赏

本文链接:https://kinber.cn/post/6338.html 转载需授权!

分享到:


推荐本站淘宝优惠价购买喜欢的宝贝:

image.png

 您阅读本篇文章共花了: 

群贤毕至

访客