301 Redirect with Express

By  on  

If you've created a site using Node.js, there's a great chance you've used the Express framework.  Express has turned into a massive project and for good reason:  it's loaded with useful functionality, an easy API, and massive community support.  On of my recent projects was using Express and I loved it!

One problem I recently needed to solve was creating a 301 redirect from an old staging domain to the new production domain.  Here's how you can create that 301 redirect with Express:

app.use(function forceLiveDomain(req, res, next) {
  // Don't allow user to hit Heroku now that we have a domain
  var host = req.get('Host');
  if (host === 'serviceworker-cookbook.herokuapp.com') {
    return res.redirect(301, 'https://serviceworke.rs/' + req.originalUrl);
  }
  return next();
});

Surprisingly the redirect code is the first argument to redirect instead of the URL.  It's important to call next() at the end of the function or a non-match will make your app hang!

Recent Features

  • By
    From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...

  • By
    Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today's websites and devices become ever more varied, a plethora of responsive images...

Incredible Demos

  • By
    Translate Content with the Google Translate API and JavaScript

    Note:  For this tutorial, I'm using version1 of the Google Translate API.  A newer REST-based version is available. In an ideal world, all websites would have a feature that allowed the user to translate a website into their native language (or even more ideally, translation would be...

  • By
    MooTools: Set Style Per Media

    I'd bet one of the most used MooTools methods is the setStyle() method, which allows you to set CSS style declarations for an element. One of the limitations of MooTools' setStyle() method is that it sets the specific style for all medias.

Discussion

  1. Great code snippet and saved me a ton of time. Thanks!

  2. Joe

    You shouldn’t have the trailing slash after serviceworke.rs. I.e. instead of this:

    res.redirect(301, 'https://serviceworke.rs/' + req.originalUrl);
    

    It should be this:

    res.redirect(301, 'https://serviceworke.rs' + req.originalUrl);
    

    Otherwise it redirects to:

    https://serviceworke.rs//the/path
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!