如何使用hapi.js在同一台服务器上支持多个网站?
假设我想用同一个IP地址(即虚拟主机)在同一台服务器上托pipe我的两个网站(cats.com和dogs.com)。 我想用hapi.js写他们,并让他们作为一个单独的进程运行。
这些网站可能有重叠的path,例如它们可能都有一个/about
页面。
我怎么能用hapi来实现呢?
用hapi实现这个function的一个很好的方法就是把不同的网站放在一起来分开插件,并且在加载插件的时候使用vhost
修饰符,理想情况下使用Glue 。
这是一个例子:
网站/ 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' };
网站/ 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'); }); });
然后您可以使用几个cURL命令来确认路由工作正常:
$ curl -H "Host: cats.com" localhost:4000/ Cats homepage $ curl -H "Host: dogs.com" localhost:4000/ Dogs homepage
浏览器将为您设置该主机头,虽然如此当您浏览到http://cats.com或http://dogs.com hapi将为您提供正确的内容(如果您的DNSconfiguration正确)。