Note that there are some explanatory texts on larger screens.

plurals
  1. POExpressJS Server - How to handle multiple domains
    text
    copied!<p>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.</p> <p>Lets assume we have </p> <ul> <li>foo.com</li> <li>bar.net</li> <li>baz.com</li> </ul> <p>which all point to <code>111.222.333.444</code>. That machine is running NodeJS with Express. My current solution looks like this:</p> <pre><code>var express = require( 'express' ), app = module.exports = express.createServer(), // ... more lines ... app.get( '/', routes.index.bind( app ) ); </code></pre> <p>Thus far this is pretty straightforward. The only exception so far is in my <code>app.configure</code> call, where I didn't make a call to <code>.use( express.static() )</code>. Thats because the <code>.routes.index()</code> method looks like so right now:</p> <pre><code>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 ); } }; </code></pre> <p>What happens here is, that I analyse the <code>req.header</code> for the <code>host</code> entry and parse the domain name. Based on that, I call the <code>.static()</code> method so <em>Express</em> can serve the right static resources etc., furthermore, I just simply read and send the contents of the <em>index.html</em> files. I tried to use <em>Jade</em> aswell for serving plain <em>HTML files</em>, but the <code>include</code> directive in <em>Jade</em> only accepts relative pathes.</p> <p>However, this indeed works, but I'm pretty unsure if that is a good practice. </p> <p>Any advice / help welcome.</p> <hr> <p><strong>Update</strong></p> <p>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.</p> <p>Thanks :-)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload