Search code examples
node.jsexpresssubdomainconnect.js

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

Can someone help ?


Solution

  • 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.