NodeJS 将所有非 www 重定向到 www 除了子域


关于

如何在Express 3.0中做到这一点的任何想法?由于非www网址在网站的不同区域引起了非常奇怪的问题。

谢谢!

答案对我不起作用。
我使用了以下代码 (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();
});

注意:这会将 www 重定向到非 www,如果您想要相反的情况,请删除if条件下的not,然后将host = host.replace(/^www./i, '');替换为host = 'www.' + host;

所以我从另一个问题中找到了答案。

节点.js:301重定向非www无快递

抱歉之前没有搜索

app.get ('/*', function (req, res, next){
  if (!req.headers.host.match(/^www./)){
      res.writeHead (301, {'Location': 'http://mysite.com'});
  }else{ 
     return next();
  }
});

最新更新