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

 

This page was generated at 9:56 PM on 15 Jan 2016.
Copyright © 1999 - 2016 Rodney Waldhoff.