Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express - set up different routes for different subdomains

I have an app running that I would like to have different routing for different subdomains. This is what I have tried:

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

but that doesn't seem to actually work. I get a 404 error. When I set app.use('/', routes); outside of that block, routes work, but then I can't set them based on subdomain. I'm guessing the problem is that I'm trying to define the routes inside an already set route, but I'm not sure how else to go about setting these routes conditionally. How can I achieve this?

like image 987
jordan Avatar asked Sep 29 '22 13:09

jordan


1 Answers

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

It looks like it covers your use case perfectly.

You could also just use a different node process per subdomain and performing routing in nginx or Apache to the applicable process.

like image 166
Evan Shortiss Avatar answered Oct 18 '22 08:10

Evan Shortiss