Force www or non-www in Express/ Connect

Serving your website through either your domain prefixed by “www”, or by your domain directly (but not both) is important for SEO. For ease-of-use (i.e so as not to drive away users), it is common practice to redirect the domain you chose not to be the canonical domain to redirect to your canonical domain.

In Apache this is accomplished via your .htaccess file. No provisions exist to do this automatically in Connect or Express, but it is easy to add middleware to achieve this.

Basically, examine the host property of the request object, and call redirect on the response object to redirect to the canonical domain if necessary.

To force “www”:

var express = require('express'),
    app = express();

app.use(function (req, res, next) {
  if (req.host.indexOf("www.") !== 0) {
    res.redirect(301, req.protocol + "://www." + req.host + ":80" + req.originalUrl);
  } else {
    next();
  }
});

To force non-“www”:

var express = require('express'),
    app = express();

app.use(function (req, res, next) {
  var str = "www.";

  if (req.host.indexOf(str) === 0) {
    res.redirect(301, req.protocol + "://" + req.host.slice(str.length) + ":80" + req.originalUrl);
  } else {
    next();
  }
});

Notes:

  1. Do not forget to call next() in the event of a redirect not being needed.
  2. Ensure you are emitting a 301 (permanent redirect) rather than any other HTTP status code.
  3. Here’s an example of how I’ve used a variant of this code in practice in my own code (using the vhost module).
  4. If you’re running on port 80, you can remove the + ":80" + portion of the code within the redirect() call; if you’re running on a different port however, change “80” to be your port.

Leave a Reply

Your email address will not be published. Required fields are marked *