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
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

Incredible Demos

  • By
    Generate Dojo GFX Drawings from SVG Files

    One of the most awesome parts of the Dojo / Dijit / DojoX family is the amazing GFX library.  GFX lives within the dojox.gfx namespace and provides the foundation of Dojo's charting, drawing, and sketch libraries.  GFX allows you to create vector graphics (SVG, VML...

  • By
    MooTools FontChecker Plugin

    There's a very interesting piece of code on Google Code called FontAvailable which does a jQuery-based JavaScript check on a string to check whether or not your system has a specific font based upon its output width. I've ported this functionality to MooTools. The MooTools...

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!