Expressjs重定向到https(使用Cloudflare Flexible SSL)

mdv*_*mdv 3 https node.js express

即时通讯使用Expressjs(NodeJS框架),我想将所有流量重定向到https,我不使用SSL证书,但Cloudflare灵活的ssl.

我正在使用这个中间件:

//FORCE SSL
app.use(function(req, res, next) {
  if(!req.secure) {
    return res.redirect(['https://', req.get('Host'), req.url].join(''));
  }
  next();
});
Run Code Online (Sandbox Code Playgroud)

我以这种方式启动应用程序:

//Firing Up express
//====================================================================
app.set('port', process.env.PORT || 80);
var server = app.listen(app.get('port'), function() {
   console.log('[-]');
   console.log(('[+] Express server listening on port '+ server.address().port).green);
   console.log('[-]');
});
Run Code Online (Sandbox Code Playgroud)

应用程序重定向到https://但无法加载

谷歌Chrome控制台说:

Failed to load resource: net::ERR_CONNECTION_REFUSED https://beta.domain.io/
Failed to load resource: net::ERR_CONNECTION_CLOSED https://beta.domain.io/
Failed to load resource: net::ERR_CACHE_MISS 
Run Code Online (Sandbox Code Playgroud)

有人能指出我正确的方向吗?

提前致谢.

Dan*_*iel 6

CloudFlare的服务器实际上是通过不安全的http与您的服务器通信.然后,它通过https将响应转发给客户端.由于与服务器的所有连接都是http,因此您的应用会重定向所有内容.在这种情况下,永远不会有有效的响应,因此无法加载.

当代理服务器连接到您的Web服务器时,它们会通过http标头传递有关客户端连接的其他信息.你应该寻找两个标题.X-Forwarded-For和X-Forwarded-Proto.X-Forwarded-For会告诉您原始客户端的IP地址是什么,X-Forwarded-Proto会告诉您原始客户端使用的协议.

在您的情况下,您希望查看X-Forwarded-Proto标头,如果是,http则重定向到等效https资源.

//FORCE SSL
app.use(function(req, res, next) {
  if(req.headers['x-forwarded-proto']==='http') {
    return res.redirect('https://' + req.headers.host + req.url);
  }
  next();
});
Run Code Online (Sandbox Code Playgroud)