表达4.x将http重定向到https

ura*_*ray 16 javascript redirect http node.js express

我有以下代码:

var https        = require('https');
var http         = require('http');
var express      = require('express');
var app          = express();
var router       = express.Router();

app.use('/', router);

//listen server on https
var server = https.createServer(config.sslCredential, app);
server.listen(config.serverPort);

//listen server on http, and always redirect to https
var httpServer = http.createServer(function(req,res){
    res.redirect(config.serverDomain+req.url);
});
httpServer.listen(config.httpServerPort);
Run Code Online (Sandbox Code Playgroud)

但不知怎的,我无法将https请求重定向到https请求,我应该如何正确地使用express 4.x在node.js上执行此操作?

Pla*_*ato 31

我自己的回答引用中间件解决方案(顺便提一下,快递3.0)

app.all('*', ensureSecure); // at top of routing calls

http.createServer(app).listen(80)
https.createServer(sslOptions, app).listen(443)

function ensureSecure(req, res, next){
  if(req.secure){
    // OK, continue
    return next();
  };
  // handle port numbers if you need non defaults
  // res.redirect('https://' + req.host + req.url); // express 3.x
  res.redirect('https://' + req.hostname + req.url); // express 4.x
}
Run Code Online (Sandbox Code Playgroud)

  • 就像使用Heroku的任何人一样,"`req.secure```将无效.请在此处查看答案:http://stackoverflow.com/questions/32952085/express-js-redirect-to-https-and-send-index-html (8认同)
  • 从2017年5月开始,使用Express v 4.8.0:`function ensureSecure(req,res,next){if(req.headers ['x-forwarded-proto'] ==='https'){//好的,继续返回next()}; res.redirect('https://'+ req.headers.host)}` (5认同)
  • `req.host`(express 3.x)现在是`req.hostname`(表示4.x) (4认同)
  • @PhilAndrews使用req.headers ['x-forwarded-proto']的解决方案仅在Express服务器位于负载均衡器后面时才有效,该负载均衡器会注入头x-forwarded-proto (4认同)