背景
有一个node项目,由于某些原因,需要把所有http
请求重定向到https
。
过程
需求很简单,开搞~
因为node是express框架的,这种操作理所应该在中间件中做, 在我们的入口文件中添加:
var protocolRedirect = function (req, res, next) {
const { protocol, header, originalUrl} = req;
// 如果是线上环境,并且是http协议的话就跳走
if (isOnline && protocol==='http') {
res.redirect(`https://${headers.host}${originalUrl}`);
}
next()
};
app.use(protocolRedirect);
Nice,本地调试,没有问题~ 部署到沙箱环境。
这里说一下我们的沙箱环境有一层nginx转发,支持https以及http协议进行接口的访问。
部署完毕,check一下~ 访问服务对应的页面 http://域名.com/home
,发现控制台不停的发302重定向请求。就很奇怪,,明明代码里会让他重定向到https
,之后就不会重定向了啊,查了查req.protocol
确实是获取协议的属性,也确实是http
。

登录到服务器打日志进行查看,发现日志里输出的protocol
确实是http
, 此时我用浏览器访问https://域名.com/home
,居然还是会输出http
。。。
这可就不对了啊!!明明请求的是https啊!!
解决
打开google,一顿搜索,发现这种在(nginx)转发代理后的服务,需要将trust proxy
设置成true
才能正常的拿到想要的protocol
,结合下实际情况,我们的沙箱有一层nginx,而且由于是内网,当https请求来到nginx之后,nginx会将请求转换成http在到服务器,所以直接拿req.protocol
只能取出http
;

放上最终代码:
var protocolRedirect = function (req, res, next) {
const { headers, originalUrl } = req;
if (!isOnline || (isOnline && req.secure)) {
next();
} else {
res.redirect(301, `https://${headers.host}${originalUrl}`);
}
};
app.enable('trust proxy');
app.use(protocolRedirect);
网友评论