A good way to achieve this with hapi is to put your different sites in the plugins section and use the vhost
modifier when loading the plugin, ideally using Glue .
Here is an example:
sites /dogs.js
exports.register = function (server, options, next) { // Put all your routes for the site in here server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('Dogs homepage'); } }); next(); }; exports.register.attributes = { name: 'dogs' };
sites /cats.js
exports.register = function (server, options, next) { // Put all your routes for the site in here server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('Cats homepage'); } }); next(); }; exports.register.attributes = { name: 'cats' };
index.js
const Glue = require('glue'); const Hoek = require('hoek'); const manifest = { connections: [{ port: 4000, }], registrations: [ { plugin: { register: './sites/cats' }, options: { routes: { vhost: 'cats.com' } } }, { plugin: { register: './sites/dogs' }, options: { routes: { vhost: 'dogs.com' } } } ] }; const options = { relativeTo: __dirname }; Glue.compose(manifest, options, (err, server) => { Hoek.assert(!err, err); server.start((err) => { Hoek.assert(!err, err); console.log('server started'); }); });
You can then confirm that routing is working correctly with a pair of cURL commands:
$ curl -H "Host: cats.com" localhost:4000/ Cats homepage $ curl -H "Host: dogs.com" localhost:4000/ Dogs homepage
The browser will set the Host header for you, although when you go to http://cats.com or http://dogs.com, hapi will provide you with the correct content (if your DNS is configured correctly).