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


Question

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 m.mysite.com, sync.mysite.com

Can someone help ?

1
51
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 */
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.

115
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 > 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 
});

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