【问题标题】:NodeJS Redirect all non-www to www except subdomainsNodeJS将所有非www重定向到除子域之外的www
【发布时间】:2013-10-28 16:30:40
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: javascript node.js web express no-www


    【解决方案1】:

    答案对我不起作用。
    我使用了以下代码(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:这会将www重定向到非www,如果您想要相反,请删除if条件上的not,然后将host = host.replace(/^www\./i, '');替换为host = 'www.' + host;

    【讨论】:

      【解决方案2】:

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

      Node.js: 301 redirect non-www without express

      抱歉之前没有搜索

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 2015-08-29
        • 1970-01-01
        • 2015-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多