2016-02-29 10 views
5

Diciamo che voglio ospitare i miei 2 siti Web (cats.com e dogs.com) sullo stesso server con un singolo indirizzo IP (cioè con host virtuali). Voglio scriverli entrambi con hapi.js e farli funzionare come un singolo processo.Come posso supportare più siti Web sullo stesso server con hapi.js?

I siti possono avere percorsi sovrapposti, ad esempio possono entrambi avere una pagina .

Come è possibile implementarlo con hapi?

risposta

3

Un buon modo per raggiungere questo con hapi è mettere i diversi siti in per separare plugins e utilizzare il modificatore vhost durante il caricamento del plug-in, idealmente utilizzando Glue.

Ecco un esempio:

siti/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' }; 

siti/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'); 
    }); 
}); 

Si può quindi confermare che il percorso funziona correttamente con un paio di cURL comandi:

$ curl -H "Host: cats.com" localhost:4000/ 
Cats homepage 

$ curl -H "Host: dogs.com" localhost:4000/ 
Dogs homepage 

Un browser imposterà tale intestazione Host per voi anche se in modo che quando si passa a http://cats.com o http://dogs.com hapi vi servirà il contenuto corretto (a condizione che il tuo DNS sia configurato correttamente).

+0

Come si servono i modelli? – eosimosu

Problemi correlati