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 4:16 PM on 26 Feb 2018.
Copyright © 1999 - 2018 Rodney Waldhoff.