NodeJS Redirect all non-www to www except subdomains

ぐ巨炮叔叔 提交于 2019-12-01 22:48:48

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;

Manak Kapoor

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();
  }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!