繁体   English   中英

将www重定向到Express服务器中的https

[英]Redirect www to https in express server

我已经安装了快速服务器,没有任何问题,但是如果我尝试将www.example.com路由到https,将会很困难。

我创建了https服务器,它在默认端口443上侦听并表示在默认端口80上侦听。

如果我输入example.com重定向到https://example.com,但是如果我输入www.example.com则它不安全,因此在这里我需要重定向到https://examle.com 我尝试过但没有用的东西。

app.get( '/', function(req, res, next) {
     if((req.get('X-Forwarded-Proto') !== 'https')) {
        res.redirect('https://' + req.get('Host') + req.url);
    } else {
        next();
    }
})

这是我尝试过的简单代码

var enforce = require('express-sslify');

app.use(express.static('./dist/restraunt'));
app.use(enforce.HTTPS());
app.use(redirectUnmatched);

app.listen(port);
https.createServer(options, app).listen(443);

function redirectUnmatched(req, res) {
    res.redirect("https://example.com");
}

如果您要将www重定向到https,那么这里是解决方案

在您的app.js中放置以下代码

app.get('*', function (req, res, next) {

      var checkHost = req.get('host').substring(0, 4);
      var condition = req.get('x-forwarded-proto') !== "https" || checkHost !== 'www.' || ( req.get('host').indexOf('www.') < 0);//
      if (condition) {
          res.set('x-forwarded-proto', 'https');

          if (checkHost === 'www.' && ( req.get('host').indexOf('www.') >= 0)) {
              res.redirect('https://' + req.get('host') + req.url);
          }
          else {
              res.redirect('https://www.' + req.get('host') + req.url);
          }
      } else {
          next();
      }
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM