Vadim was almost onto the right idea. You can configure how to respond to each domain with the vhost middleware:
// `baz.com`
var app = express.createServer();
app.get( "https://stackoverflow.com/", routes.index );
// ...
express.createServer()
.use( express.vhost( 'foo.com', express.static( '/var/www/foo' ) ) )
.use( express.vhost( 'bar.net', express.static( '/var/www/bar' ) ) )
.use( express.vhost( 'baz.com', app ) )
.use( function( req, res ) {
res.send('Sorry, I do not know how to handle that domain.');
})
.listen( ... );
routes.index can then be simplified to handle only baz.com requests:
exports.index = function( req, res ) {
// ... lines ...
res.render( 'index', { title: 'Baz Title example' } );
};
Edit
As for comparisons:
The switch would effectively be done first and would determine how to handle all requests based on the host — similar to:
express.createServer().use(function( req, res, next ) {
switch( req.host ) {
case 'foo.com': express.static( '/var/www/foo' )( req, res, next ); break;
case 'bar.net': express.static( '/var/www/bar' )( req, res, next ); break;
case 'baz.com': app.handle( req, res, next ); break;
default: res.send( ... );
}
}).listen( ... );
It allows you to set the stack on start so any middleware is available immediately:
server.stack = [
express.vhost( 'foo.com', ... ),
express.vhost( 'bar.net', ... ),
express.vhost( 'baz.com', ... ),
[Function]
];
These also reflect the 2 possible sources of issues you might have:
Same stack without filters
Each Application only has 1 middleware stack, which all of the middleware you’re using is being added directly to with app.use(...). Despite adding some under conditions, you’re still getting:
app.stack = [
// ...,
app.router,
express.static( '/var/www/foo' ),
express.static( '/var/www/bar' )
];
And the condition won’t change how the static middlewares respond — which is by req.path, not req.host — only when they’re in the stack to start responding.
State of the stack
And, if the static middlewares aren’t added until after another request has been made, then I take it they aren’t available immediately:
// GET http://foo.com/file 404
app.stack = [ app.router ]
// GET http://foo.com/ 200
app.stack = [ app.router, express.static( '/var/www/foo' ) ]
// GET http://foo.com/file 200
app.stack = [ app.router, express.static( '/var/www/foo' ) ]
This may also mean the same static middleware could be added to the stack multiple times:
// 3x GET http://foo.com/
app.stack = [
app.router,
express.static( '/var/www/foo' ),
express.static( '/var/www/foo' ),
express.static( '/var/www/foo' )
]
And having their addition depend on other requests also suggests a possible race conditions:
// was `foo.com` or `bar.net` first?
app.stack = [
app.router,
express.static( ? ),
express.static( ? )
]