Issue
Let's say I want to host my 2 websites (cats.com and dogs.com) on the same server with a single IP address (i.e. with virtual hosts). I want to write them both with hapi.js and have them running as a single process.
The sites may have overlapping paths, for instance they might both have a /about
page.
How could I implement this with hapi?
Solution
A nice way of achieving that with hapi is by putting your different sites in to separate plugins and using the vhost
modifier when loading the plugin, ideally using Glue.
Here's 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 the routing works correctly with a couple of cURL commands:
$ curl -H "Host: cats.com" localhost:4000/
Cats homepage
$ curl -H "Host: dogs.com" localhost:4000/
Dogs homepage
A browser will set that Host header for you though so when you browse to http://cats.com or http://dogs.com hapi will serve you the correct content (provided your DNS is configured correctly).
Answered By - Matt Harrison Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.