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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With