2013-10-20 99 views

回答

3

所以我找到了另一個問題的答案。

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(); 
    } 
}); 
5

答案沒有工作對我來說不是搜索。
我用下面的代碼(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;

+0

非常感謝。 – kalin

相關問題