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


I am used to working on httpd ( Apache ) which provides a way to configure subdomains which is mapped to a directory. How can I do the same thing in Connect.js/Express.js ? I see that the only thing that I have is routes which I am not sure how I can use to configure sub domains. I have subdomains like,

Can someone help ?

12/18/2014 7:35:44 PM

Accepted Answer

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 */ = app
// There is no need for .listen()

And then handle all requests with the following app:

var vhost = require('vhost');

.use(vhost('', require('/path/to/m').app))
.use(vhost('', require('/path/to/sync').app))

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

11/12/2015 8:45:24 AM

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

I got the following code from > (so full credit to the original author)

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

// 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 

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow