How do I create a hapi http
and https
server, listening on both 80 and 443 with the same routing?
(I need a server which should run both on http and https with the exact same API)
To create an HTTPS server, you need two things: an SSL certificate, and built-in https Node. js module. We need to start out with a word about SSL certificates. Speaking generally, there are two kinds of certificates: those signed by a 'Certificate Authority', or CA, and 'self-signed certificates'.
It may not be usual to handle the https requests directly on the application, but Hapi.js can handle both http and https within the same API.
var Hapi = require('hapi');
var server = new Hapi.Server();
var fs = require('fs');
var tls = {
key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem')
};
server.connection({address: '0.0.0.0', port: 443, tls: tls });
server.connection({address: '0.0.0.0', port: 80 });
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.start(function () {
console.log('Server running');
});
You can redirect all http requests to https instead :
if (request.headers['x-forwarded-proto'] === 'http') {
return reply()
.redirect('https://' + request.headers.host + request.url.path)
.code(301);
}
Check out https://github.com/bendrucker/hapi-require-https for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With