I'm fooling around a little with Express and I'm wondering, what the "most correct" way is to handle multiple domains which are linked to the same server.
Lets assume we have
- foo.com
- bar.net
- baz.com
which all point to 111.222.333.444. That machine is running NodeJS with Express. My current solution looks like this:
var express = require( 'express' ),
app = module.exports = express.createServer(),
// ... more lines ...
app.get( '/', routes.index.bind( app ) );
Thus far this is pretty straightforward. The only exception so far is in my app.configure call, where I didn't make a call to .use( express.static() ). Thats because the .routes.index() method looks like so right now:
var fs = require( 'fs' ),
// ... more lines ...
exports.index = function( req, res ) {
var host = /(\w+\.)?(.*)\.\w+/.exec( req.header( 'host' ) ),
app = this;
switch( host[ 2 ] ) {
case 'foo':
app.use( express.static( '/var/www/foo' ) );
fs.readFile( '/var/www/foo/index.html', 'utf8', fileReadFoo );
break;
case 'bar':
app.use( express.static( '/var/www/bar' ) );
fs.readFile( '/var/www/bar/index.html', 'utf8', fileReadBar );
break;
case 'baz':
// ... lines ...
res.render( 'index', { title: 'Baz Title example' } );
break;
default:
res.send('Sorry, I do not know how to handle that domain.');
}
function fileReadFoo( err, text ) {
res.send( text );
}
function fileReadBar( err, text ) {
res.send( text );
}
};
What happens here is, that I analyse the req.header for the host entry and parse the domain name. Based on that, I call the .static() method so Express can serve the right static resources etc., furthermore, I just simply read and send the contents of the index.html files. I tried to use Jade aswell for serving plain HTML files, but the include directive in Jade only accepts relative pathes.
However, this indeed works, but I'm pretty unsure if that is a good practice.
Any advice / help welcome.
Update
I think I need to make this more clear. I'm not a beginner by any means. I'm very aware how ES works and other servers like NGINX. I'm looking for qualified answers on what the right thing with NodeJS/Express is. If it doesn't make any sense to use Node/Express for that, please elaborate. If there is a better way to do this with Node/Express, please explain.
Thanks :-)