Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect non-www to www with Node.js and Express

I am serving a static directory like so:

var app = express.createServer();
app.configure(function(){
    app.use(express.static(__dirname + '/public'));
});

So I am not using routes at all. I would like to redirect example.com to www.example.com, is this possible using Express?

like image 263
Tom Avatar asked Feb 03 '12 17:02

Tom


4 Answers

The following code preserve path while redirecting

Ex: http://foo.com/foo to http://www.foo.com/foo

    var app = express.createServer();
    self.app.all(/.*/, function(req, res, next) {
      var host = req.header("host");
      if (host.match(/^www\..*/i)) {
        next();
      } else {
        res.redirect(301, "http://www." + host + req.url);
      }
    });
    app.use('/',express.static('public'));
like image 58
karthikdivi Avatar answered Nov 19 '22 20:11

karthikdivi


Alternatively, you can use a ready-made module for Express that does exactly what you want, e.g. node-force-domain.

See https://github.com/goloroden/node-force-domain for details.

like image 33
Golo Roden Avatar answered Nov 19 '22 20:11

Golo Roden


Yes. This should do it.

var express = require("express");
var app = express.createServer();
var port = 9090;
app.all(/.*/, function(req, res, next) {
  var host = req.header("host");
  if (host.match(/^www\..*/i)) {
    next();
  } else {
    res.redirect(301, "http://www." + host);
  }
});
app.use(express.static(__dirname + "/public"));
app.listen(port);
like image 11
Peter Lyons Avatar answered Nov 19 '22 21:11

Peter Lyons


You can use express-force-domain package from npm:

//install
npm install express-force-domain

///app.js
app.all('*', require('./express-force-domain')('http://www.example.com') );

Package on npm: https://npmjs.org/package/express-force-domain

like image 3
chovy Avatar answered Nov 19 '22 22:11

chovy