在 Hapi.js 中将 http 重定向到 https

Redirect http to https in Hapi.js

我的 hapi 服务器确实有以下配置

const server = new Hapi.Server();

const tls = {
  cert: fs.readFileSync(path.join(__dirname, '../certificates/cert.crt')),
  key: fs.readFileSync(path.join(__dirname, '../certificates/cert.key')),
};

server.connection({
  port: process.env.PORT_HTTP || 80,
  host: process.env.HOST || 'localhost',
});

server.connection({
  port: process.env.PORT_HTTPS || 443,
  host: process.env.HOST || 'localhost',
  tls,
});

服务器在 httphttps 上都工作正常,但我想将所有流量从 http 重定向到 https

我该如何继续,已经尝试注册 hapi-require-https npm 模块,但流量仍然保持不变,没有任何反应。

为 http 请求创建一个额外的服务器并将它们绑定到 redirect 函数。

var Hapi = require('hapi');
var http = new Hapi.Server(80);
var server = new Hapi.Server(443, { tls: {} });

var redirect = function () {

    this.reply.redirect('https://your.site/' + this.params.path);
});

http.route({ method: '*', path: '/{path*}', handler: redirect });

更新(其他选项)

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

        if(request.headers.referer.split(':')[0] == "http"){
           this.reply.redirect('https://your.site' + this.params.path);
        }
    }
});

这个怎么样?绑定它们

var http = new Hapi.Server(80); // our extra server
http.route({ 
method: '*', 
path: '/{path*}', 
handler: 
      function (request, reply) {

       // if(request.headers.referer.split(':')[0] == "http"){
           this.reply.redirect('https://your.site' + this.params.path);
       // }
    }
});

创建两个服务器实例来分别处理 http 和 https 流量。

var Hapi = require('hapi');
var server = new Hapi.Server(80);
var httpsServer = new Hapi.Server(443, { tls: { // your certificates here} });

现在将 hapi-gate 插件注册到基础服务器,以便它将流量重定向到 https。

server.register({
  register: require('hapi-gate'),
  options: {https: true} // will force https on all requests
}); 

您也可以改用 hapi-require-https 插件。