Reputation: 189
I want to set root directory of exress.static in a way that request from a subdomain will have separate root folder.
I have a site with multiple subdomain, and the structure is a following
index.js
public/
-- site1
-- site2
-- site3
i want to set public/site1
as static folder when request is from site1.mydomain.com
and site2.mydomain.com
should not be able to get files from public/site1
directory.
I have tried this:
app.use ((req, res, next) => {
let hostName = req.headers.host;
let options = domainMap[hostName];
req.app.use (
express.static (path.join (__dirname, 'public', options.publicDir))
);
next ();
});
domainMap holds the following object:
{
site1:{
publicDir:'site1',
},
site2:{
publicDir:'site2',
},
site3:{
publicDir:'site3',
}
}
what it does now is it sets the public directory only for the first request, but is there any way to change i dynamically for every request ?
Upvotes: 4
Views: 1080
Reputation: 707218
You can generate the desired middleware function dynamically and then call it manually. You don't want to register it with app.use()
because then it will be active for all requests. That's why you need to call it manually. Also, express.static()
generates a middleware that already calls next()
so you don't need to do that either except in cases where you don't call the generated middleware.
app.use ((req, res, next) => {
let hostName = req.headers.host;
let options = domainMap[hostName];
// protect against missing or unexpected hostName
if (options && options.publicDir) {
let middleware = express.static(path.join (__dirname, 'public', options.publicDir));
middleware(req, res, next);
} else {
// nothing to do here, keep routing
next();
}
});
Upvotes: 4