express 4.x redirect http to https

前端 未结 1 1525
暖寄归人
暖寄归人 2020-12-14 17:38

i have the following code :

var https        = require(\'https\');
var http         = require(\'http\');
var express      = require(\'express\');
var app             


        
相关标签:
1条回答
  • 2020-12-14 18:09

    Quoting a middleware solution from my own answer (which btw was on express 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
    }
    
    0 讨论(0)
提交回复
热议问题