Snippets are tiny notes I've collected for easy reference.
Redirect www.example.com to example.com in Node.js and Express.js
To redirect all paths on the "www" version of a hostname to the "non-www" (domain only) version using Express.js (or Connect):
JavaScript:
app.all('/*', function(req, res, next) {
if(/^www\./.test(req.headers.host)) {
res.redirect(req.protocol + '://' + req.headers.host.replace(/^www\./,'') + req.url,301);
} else {
next();
}
});
CoffeeScript:
app.all '/*', (req, res, next)->
if /^www\./.test req.headers.host
res.redirect "#{req.protocol}://#{req.headers.host.replace(/^www\./,'')}#{req.url}",301
else
next()
Published 13 Mar 2014
Snippets are tiny notes I've collected for easy reference.