Reputation: 173
So i know this works:
app.use(express.vhost('sub.xyz.com', subdomainApp));
app.use(express.vhost('xyz.com', mainApp));
But when i try set the host part in express.vhost dynamically, it simply doesn't work. (I need to set it dynamically in order to avoid changing the hard coded domains while i move between production and development.)
I tried the code below and i dont know why this doesn't work:
app.use(function(req, res){ return express.vhost('xyz.'+req.host, subdomainApp); });
app.use(function(req, res){ return express.vhost(req.host, mainApp); });
So how do i pass 'request host' dynamically to express.vhost?
Upvotes: 3
Views: 1507
Reputation: 24352
Use *
as a wildcard in the hostname:
app.use(express.vhost('sub.*', subdomainApp));
app.use(mainApp);
See http://www.senchalabs.org/connect/vhost.html.
Upvotes: 0
Reputation: 11052
I misread your question so my answer is about programmatically binding vhosts. I don't know if you can bind new vhosts on the fly as requests come in, it sounds like a bad idea. I would just use @alfonsodev 's technique to force one environment or the other.
if you have a set of known subdomains and particular middlewares you want to execute for those domains, you could bind them all like this:
$ # set env variable before invoking the script
$ APP_DEVPROD=dev node server.js
// Default to 'prod' if no env var set
var p = process.env.APP_DEVPROD || 'prod';
var myHost = (p === 'dev' ? 'localhost:8001' : 'xyz.com');
[
['admin.'+myHost, handlers.admin],
['demo.'+myHost, handlers.demo],
].forEach(setVhost);
function setVhost(pair){
var hostname = pair[0];
var appFn = pair[1];
app.use(express.vhost(hostname, appFn));
}
Upvotes: 2
Reputation: 2754
I don't know exactly your implementation details, but what I suggest and I think it's the most common practice, is to set those configuration params in envrionment variables.
so you would have.
app.use(express.vhost('xyz' + process.env.APP_HOST, subdomainApp));
so you can have different env vars in production / development environments.
to set env variables from command line use
export APP_HOST=wahtever
or append just before execute the node command
APP_HOST=whatever node server.js
or add them to your *.bash_profile* or equivalent for your OS
Upvotes: 2