我尝试从www重定向到非www,但不能。 看看我的代码:
function wwwRedirect(req, res, next) {
console.log('Got url ' + req.headers.host) // return example.com (without 'www'), even if I go to www.example.com
console.log('req.get("host") ' + req.get('host')) // same
if (req.headers.host.slice(0, 4) === 'www.') { // not working, cause req.headers.host doesn't contain 'www', even if Im connecting to www.example.com
var newHost = req.headers.host.slice(4);
return res.redirect(301, req.protocol + '://' + newHost + req.originalUrl);
console.log('New url ' + req.protocol + '://' + newHost + req.originalUrl)
}
next();
};
app.set('trust proxy', true);
app.use(wwwRedirect);
请查看上面的所有评论。 所以,我无法进行重定向。我究竟做错了什么?为什么req.headers.host不包含' www。'即使我与www.example.com'
联系答案 0 :(得分:1)
您可以这样做:
app.use(function(req, res, next) {
if (req.headers.host.match(/^www/) !== null ) {
res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url);
} else {
next();
}
})