How can I configure multiple sub domains in Express.js or Connect.js

Or alternatively you could use vhost.

Then, create several sites in their own directory and export the express app, eg. /path/to/m/index.js:

var app = express()
/* whatever configuration code */
exports.app = app
// There is no need for .listen()

And then handle all requests with the following app:

var vhost = require('vhost');

express()
.use(vhost('m.mysite.com', require('/path/to/m').app))
.use(vhost('sync.mysite.com', require('/path/to/sync').app))
.listen(80)

Note that /path/to/m and /path/to/sync can be absolute paths (as written above) or relative paths.


You could append a subdomain to a request and then check for it in subsequent next() calls.

I got the following code from > http://groups.google.com/group/express-js/browse_thread/thread/b04bbaea7f0e8eed (so full credit to the original author)

app.get('*', function(req, res, next){ 
  if(req.headers.host == 'some.sub.domain.com')  //if it's a sub-domain
    req.url = '/mysubdomain' + req.url;  //append some text yourself
  next(); 
});

// This will mean that all get requests that come from the subdomain will get 
// /subdomain appended to them, so then you can have routes like this 
app.get('/blogposts', function(){ 
  // for non-subdomain 
});

app.get('/mysubdomain/blogposts', function(){ 
   // for subdomain 
});