Hapijs 在一个连接上同时使用 Http 和 Https

Hapijs using both Http and Https on one connection

Hapijs 的新手并尝试使用它来创建一个对所有请求都使用 HTTPS 并将 HTTP 重定向到安全 connection.The 的应用程序我将 URL 更改为 HTTP 服务器没有响应并且不知道原因。

这是我到目前为止想出的,它有效但不适用于 HTTP

var connectionOptions = {
    port: 3000,
    tls: {
        key: fs.readFileSync(path.join(__dirname, 'key/key.pem'), 'utf8'),
        cert: fs.readFileSync(path.join(__dirname, 'key/cert.pem'), 'utf8')
    }
};

var server = new Hapi.Server();
server.connection(connectionOptions);

//This method not called when its HTTP
server.ext('onRequest', function (request, reply) {
     if (request.headers['x-forwarded-proto'] === 'http') {
            reply.redirect('https://' + request.headers.host +
                            request.url.path).code(301);
            return reply.continue();
      }
      reply.continue();       
});

var routes = require('./routes')(server);
server.route(routes);

if (!module.parent) {
    server.start(function () {
         console.log('Server running at:', server.info.uri);
    });
 }

如何强制所有请求为 HTTPS。 谢谢你的帮助

您不能在同一连接上使用 http 和 https。在幕后,Hapi 将根据您的 tls 配置创建一个节点 http 服务器 一个 https 服务器,如 lib/connection.js:

this.listener = this.settings.listener || (this.settings.tls ? Https.createServer(this.settings.tls) : Http.createServer());

您应该创建另一个不使用 TLS 的服务器连接,然后将 non-TLS 请求重定向到 https url.

示例

const Hapi = require('hapi');
const Fs = require('fs');
const Url = require('url');

const config = {
    host: 'localhost',
    http: { port: 3001 },
    https: {
        port: 3000,
        key: Fs.readFileSync('key.key'),
        cert: Fs.readFileSync('cert.pem')
    }
}

const server = new Hapi.Server();

// https connection

server.connection({
    port: config.https.port,
    tls: {
        key: config.https.key,
        cert: config.https.cert
    }
});

// http connection

server.connection({ port: config.http.port });

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        reply('Hello world');
    }
});

server.ext('onRequest', (request, reply) => {

    if (request.connection.info.port !== config.https.port) {

        return reply.redirect(Url.format({
            protocol: 'https',
            hostname: request.info.hostname,
            pathname: request.url.path,
            port: config.https.port
        }));
    }

    return reply.continue();
});

server.start((err) => {

    if (err) {
        throw err;
    }

    console.log('Started server');
});

编辑

如果您在重定向到 HTTPS 之前允许与服务器的不安全连接,请考虑使用 HTTP Strict Transport Security (HSTS) 来防止 MITM 攻击。您可以使用路由配置 security 选项设置 HSTS headers:

server.route({
    config: {
        security: {
            hsts: {
                maxAge: 15768000,
                includeSubDomains: true,
                preload: true
            }
        }
    },
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        ...
    }
});

另一种解决方案只是重新路由每个 http 调用,不检查每个请求。 不过您必须使用 2 个连接。

// create the 2 connections and give the http one a specific label e.g. http
// apply the http catch all route to only the http connection
// I make use of connection label to make sure I only register the catch all route on the http connection
server.select('http').route({
    method: '*',
    path: '/{p*}',
    handler: function (request, reply) {

        // redirect all http traffic to https
        // credit to Matt for the URL.format
        return reply.redirect(Url.format({
            protocol: 'https',
            hostname: request.info.hostname,
            pathname: request.url.path,
            port: config.https.port
        })).permanent();
    },
    config: {
        description: 'Http catch route. Will redirect every http call to https'
    }
});

有关重定向的详细信息,请参阅 the docs