NodeJS Redirect all non-www to www except subdomains

后端 未结 2 635
南旧
南旧 2021-01-21 11:52

any idea on how i can do this in Express 3.0? As the non-www url is causing very odd problems in different areas of the website.

Thanks!

相关标签:
2条回答
  • 2021-01-21 12:19

    The answer didn't work for me.
    I've used the following code (http://redirect-www.org/#nodejs):

    //REDIRECT www.domain.com TO domain.com
    app.get ('/*', function (req, res, next){
        var protocol = 'http' + (req.connection.encrypted ? 's' : '') + '://'
          , host = req.headers.host
          , href
          ;
    
        // no www. present, nothing to do here
        if (!/^www\./i.test(host)) {
          next();
          return;
        }
    
        // remove www.
        host = host.replace(/^www\./i, '');
        href = protocol + host + req.url;
        res.statusCode = 301;
        res.setHeader('Location', href);
        res.write('Redirecting to ' + host + req.url + '');
        res.end();
    });
    

    Care: this will redirect www to non-www, if you want the opposite, delete the not on the if condition and then replace host = host.replace(/^www\./i, ''); with host = 'www.' + host;

    0 讨论(0)
  • 2021-01-21 12:42

    So i found the answer from another question.

    Node.js: 301 redirect non-www without express

    Sorry for not searching before

    app.get ('/*', function (req, res, next){
      if (!req.headers.host.match(/^www\./)){
          res.writeHead (301, {'Location': 'http://mysite.com'});
      }else{ 
         return next();
      }
    });
    
    0 讨论(0)
提交回复
热议问题