如何强制所有 HTTP 请求重定向到 HTTPS?在反向代理(如 Nginx)和应用层如何配置?
解读
国内生产环境普遍把 TLS 终止放在最外层(阿里云 SLB、腾讯云 CLB、Kubernetes Ingress、Nginx 等),因此“重定向”通常由反向代理完成;但 NestJS 作为企业级框架,必须同时具备“在反向代理后面正确识别协议”和“在裸机或 Serverless 场景下自己重定向”两种能力。面试官想确认候选人是否:
- 熟悉国内云厂商常见的“七层转发 + 真实协议头”套路;
- 能在 NestJS 侧用最少代码、无副作用地兼容两种部署形态;
- 理解 301/308、HSTS、CDN 缓存等细节,避免重复重定向或缓存污染。
知识点
- 反向代理协议识别:X-Forwarded-Proto、X-Real-IP、CDN 的 X-Tencent-Ua、Ali-Cdn-Real-Ip 等
- HTTP 状态码选择:301(永久跳转,可缓存)、308(永久跳转,保留方法体)、302/307(临时)
- HSTS(Strict-Transport-Security)与浏览器预加载列表
- NestJS 中间件顺序、全局前缀、Fastify 与 Express 差异
- 国内云厂商“强制 HTTPS”开关与回源协议配置
- Serverless(阿里云 FC、腾讯云 SCF)无 80 端口时的边缘重定向方案
答案
一、反向代理层(推荐,性能最高,国内主流做法)
- Nginx 配置(TLS 终止在 Nginx)
server {
listen 80;
server_name api.xxx.com;
# 国内云厂商 SLB 会透传 X-Forwarded-Proto
if ($http_x_forwarded_proto != 'https') {
return 308 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
server_name api.xxx.com;
ssl_certificate /etc/nginx/ssl/xxx.pem;
ssl_certificate_key /etc/nginx/ssl/xxx.key;
location / {
proxy_pass http://nest-backend:3000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
要点:
- 用 308 保留 POST 方法,防止旧客户端 301 转 GET
- 必须透传 X-Forwarded-Proto,供 NestJS 内部生成正确的 self-link
- 阿里云/腾讯云 SLB 控制台 在“监听”页直接打开“强制 HTTPS 跳转”,回源协议仍选 HTTP,减少 NestJS 的 TLS 压力。
二、应用层(裸机、Serverless、边缘函数场景)
- 通用中间件(同时兼容 Express 与 Fastify)
// src/common/middleware/https-redirect.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class HttpsRedirectMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
// 国内 CDN 常用 x-forwarded-proto
const proto = req.headers['x-forwarded-proto'] || req.protocol;
if (proto === 'https') {
return next();
}
// 308 保留方法体
const target = `https://${req.get('host')}${req.originalUrl}`;
return res.redirect(308, target);
}
}
在 AppModule 全局注册:
consumer
.apply(HttpsRedirectMiddleware)
.forRoutes('*');
- Fastify 适配器下需关闭 trustProxy 默认 false
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ trustProxy: true }) // 识别 X-Forwarded-*
);
- 增加 HSTS(可选,需评估域名是否全站 HTTPS)
app.use((req, res, next) => {
res.setHeader('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload');
next();
});
三、验证
- curl -I http://api.xxx.com/health 应返回 308 Location https://...
- 浏览器 Network 面板需只出现一次 308,后续内部请求全部 200
- 阿里云 CDN 控制台“HTTPS 配置”打开“强制跳转”后,源站不再接受 80 端口请求,避免双跳
拓展思考
- 双证书场景:国内部分业务需要国密 SM2 证书,Nginx 层可基于 ssl_ciphers 分流,NestJS 无感知
- 灰度重定向:利用 NestJS 的 ConfigService 读取配置中心开关,按百分比或 UID 灰度开启 308,防止旧客户端异常
- 边缘函数重定向:阿里云 EdgeRoutine、腾讯云 ESA 支持在 CDN 边缘用 JavaScript 做 308,回源流量全走 HTTPS,进一步降低延迟
- 测试环境豁免:通过 NODE_ENV=development 或内网 IP 段白名单,关闭重定向中间件,避免本地 http://localhost 被强制跳转到 https 导致证书错误
- 监控报警:在 Prometheus 中收集 nginx_http_requests_total{status="308"} 指标,突增可能意味着爬虫或配置循环