Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Specifying routes by subdomain in Express using vhost middleware

Specifying routes by subdomain in Express using vhost middleware


I'm using the vhost express/connect middleware and I'm a bit confused as to how it should be used. I want to have one set of routes apply to hosts with subdomains, and another set to apply for hosts without subdomains.

In my app.js file, I have

var app = express.createServer();

app.use(express.vhost('*.host', require('./domain_routing')("yes")));
app.use(express.vhost('host', require('./domain_routing')("no")));


and then in domain_routing.js:

module.exports = function(subdomain){

  var app = express.createServer();

  require('./routes')(app, subdomain);

  return app;

and then in routes.js I plan to run sets of routes, dependent on whether the subdomain variable passed in is "yes" or "no".

Am I on the right track or is this not how you use this middleware? I'm a bit confused on the fact that there are two app server instances being created (as that's how examples on the web seem to do things). Should I instead pass in the original app server instance and just use that instead of creating a separate one instead the subdomain router?

Problem courtesy of: user730569


Yes, you are on the right track. You should have a different server instance for each of the vhost. Be it a http.Server or express app.

If you pass the original app, a request you sent to the vhost will be emitted to the original app. So, unless the vhost has paths which are not used in original server, it will get response as if the request was sent to original server.

From the connect docs

  .use(connect.vhost('', fooApp))
  .use(connect.vhost('', barApp))
  .use(connect.vhost('*.com', mainApp))
Solution courtesy of: Pavan Kumar Sunkara


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Specifying routes by subdomain in Express using vhost middleware


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription