nginx 反向代理实现 https to https:对外配置 ssl 证书并强制 http 跳转 https,对内通过 proxy_pass https:// 代理后端,开启 proxy_ssl_verify 并指定可信 ca 证书,同时设置超时与 x-forwarded-proto 等关键头信息。

配置 Nginx 反向代理支持 HTTPS 协议,核心是两层 HTTPS:Nginx 对外提供 HTTPS 服务(客户端 → Nginx),同时 Nginx 对内也以 HTTPS 方式访问后端(Nginx → 后端服务)。这属于“HTTPS to HTTPS”代理场景,常见于安全要求高的微服务、API 网关或与 Spring Security 等框架集成的系统。
对外启用 HTTPS(客户端到 Nginx)
这是用户访问的第一层加密,必须配置有效的 SSL 证书:
- 使用 Let’s Encrypt 自动获取证书:
sudo certbot --nginx -d yourdomain.com,Certbot 会自动修改配置并重载 Nginx - 手动配置时,在
server块中指定证书路径:ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem; - 强制跳转 HTTP 到 HTTPS(推荐):
return 301 https://$host$request_uri;放在listen 80的 server 块中
对内代理 HTTPS 后端(Nginx 到后端服务)
当后端服务本身运行在 HTTPS(如 https://192.168.1.10:8443),Nginx 需要能建立可信的 TLS 连接:
- 关键指令是
proxy_pass https://backend.example.com,协议必须写https:// - 若后端使用自签名证书或私有 CA 签发的证书,需关闭证书校验(仅限测试):
proxy_ssl_verify off; - 生产环境务必开启校验,并指定可信根证书:
proxy_ssl_trusted_certificate /path/to/ca-bundle.crt;
(该文件应包含后端服务所用 CA 的公钥) - 可选增强安全性:
proxy_ssl_protocols TLSv1.2 TLSv1.3;、proxy_ssl_ciphers HIGH:!aNULL:!MD5;
请求头与连接参数调优
HTTPS 通信比 HTTP 开销更大,需针对性调整超时和头信息传递:
- 设置合理超时(避免握手慢导致连接中断):
proxy_connect_timeout 60s;proxy_read_timeout 120s;proxy_send_timeout 120s; - 必须传递原始协议信息,否则后端可能误判为 HTTP:
proxy_set_header X-Forwarded-Proto $scheme;
(配合$scheme可确保后端知道请求来自 HTTPS) - 保留客户端真实信息:
proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
完整最小可用配置示例
以下是一个可直接部署的 /etc/nginx/conf.d/secure-proxy.conf 片段:
listen 443 ssl;
server_name api.example.com;
ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
location / {
proxy_pass https://192.168.1.100:8443;
proxy_ssl_verify on;
proxy_ssl_trusted_certificate /etc/nginx/ssl/internal-ca.crt;
proxy_ssl_protocols TLSv1.2 TLSv1.3;
proxy_connect_timeout 60;
proxy_read_timeout 120;
proxy_send_timeout 120;
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;
}
}
server {
listen 80;
server_name api.example.com;
return 301 https://$host$request_uri;
}











