Permanent Redirect Non-WWW to WWW in Node.JS on Heroku

For SEO reasons it’s important to make sure that users only visit your site through a single domain name. Either www.example.com or example.com, but not both. In most cases a .htaccess change is the easiest fix. But not when you’re deploying to an environment that doesn’t have Apache, like Heroku. Here’s a quick way to get this functionality using Express on Node.JS

Since you probably only want to do this in a production environment, I suggest you place this in that configure block.

Before you add any middleware add the following route:

1
2
3
4
5
6
7
app.get('*', function(req, res, next) {
  if (req.headers.host.slice(0, 3) != 'www') {
    res.redirect('http://www.' + req.headers.host + req.url, 301);
  } else {
    next();
  }
});

That’s really all there is to it. Since most frameworks have similar routing options, you should be able to adapt this to other frameworks, such as Geddy.

BTW I’m planning to launch a Node.JS app in November as part of Hacker News’ Launch an App Month.

This entry was posted in Java and JavaScript. Bookmark the permalink. Both comments and trackbacks are currently closed.
  • Feedback or questions? Contact me right away.

    Comments have been disabled on my posts. Not because I don't want to hear from you, but because they were adding very little to the conversation (most of them were spam anyway). I do listen to you and try to keep as much posts as possible up-to-date and error free. So if you have a question, if something isn't working the way you hoped or you have general feedback, please use the contact form below. I guarantee an answer to every honest question or remark.
  • Get in touch
    1. (required)
    2. (valid email required)
     

    cforms contact form by delicious:days