Express - set up different routes for different subdomains

I have an application where I would like to have different routing for different subdomains. This is what I tried:

app.get('*', function(req, res, next){
  if(req.headers.host == 'sub.example.com') { //if it a sub-domain
    app.use('/', sub_routes);
  }else{
    app.use('/', routes);
  }
  next();
});

      

but that doesn't seem to work. I get a 404 error. When I set app.use('/', routes);

outside of this block, the routes work, but then I cannot set them based on the subdomain. I guess the problem is that I'm trying to define routes inside an already given route, but I'm not sure how else one can provisionally configure these routes. How can I achieve this?

+3


source to share


1 answer


I've never used this, but have you tried https://www.npmjs.org/package/express-subdomain

It looks like it works great for your use.



You can also just use a different node process for each subdomain and route to nginx or Apache to the applicable process.

+3


source







All Articles