EhevuTov EhevuTov - 2 months ago 10
Node.js Question

Redirect all requests using Express 3?

What is the best way to do this?

I'd like to redirect all requests from

www.mysite.com
to
mysite.com


*.mysite.com
to
mysite.com
would be ideal

I would think some type of middleware. I still hate this, because it seems so inelegant and slightly wasteful, but I think my only option is to do this server-side.

Answer

Since Express 3 doesn't use its own HTTP server (instead you pass your app to http.createServer), it doesn't know what port it's running on unless you tell it. That said, you can do basically what you want to do with the following:

app.use(function(request, response, next) {
  var newHost = request.host.replace(/^www\./, '');
  if (request.host != newHost) {
    // 301 is a "Moved Permanently" redirect.
    response.redirect(301, request.protocol + "://" + newHost + request.url);
  } else {
    next();
  }
});

You could export this in a module and wrap it in a generator that takes a port:

// no_www.js

module.exports = function(port) {
  app.use(function(request, response, next) {
    var newHost = request.host.replace(/^www\./, '');
    if (request.host != newHost) {
      var portStr = '';
      if (request.protocol == 'http' && port != 80) portStr = ':' + port;
      if (request.protocol == 'https' && port != 443) portSt r= ':' + port;
      // 301 is a "Moved Permanently" redirect.
      respons.redirect(301, request.protocol + "://" + newHost + portStr + request.url);
    } else {
      next();
    }
  });
}

// app.js

var noWww = require('./no_www');
var app = express();

app.configure("development", function() {
  app.set("port", 3000);
});

...

app.use(noWww(app.get('port')));
Comments