【问题标题】:redirect http to https using node-red on IBM Bluemix在 IBM Bluemix 上使用 node-red 将 http 重定向到 https
【发布时间】:2018-02-08 23:48:56
【问题描述】:

在 Bluemix 上使用 node-red,我能够让我的应用程序同时在 http://example.comhttps://example.com 上运行。但是,我希望我的应用程序受到保护,并且只能使用 https 访问。在 Bluemix 上运行的 node-red 上,我找不到将 http 重定向到 https 的方法。我只找到了在 node.js/express 和其他 Web 服务器上执行此操作的方法。

我还尝试通过检测msg.req.headers.$wssc 对我的应用程序进行重定向,并使用http 请求节点重定向到https url,但它不起作用(仍然得到http 响应)。

在 DNS 上配置重定向也不是一个选项,因为 AFAIK,您不能将 http://example.com 重定向到 https://example.com,但您可以将 http://example.com 重定向到 https://www.example.com

请提出建议。

【问题讨论】:

    标签: ibm-cloud node-red


    【解决方案1】:

    您应该能够通过使用 msg.req.headers.x-forwarded-proto 值然后发送具有 301 状态的响应来做到这一点,例如

    if (msg.req.headers['x-forwarded-proto'] == 'http') {
      msg.statusCode = 301;
      msg.headers = {
        location: 'https://' + msg.req.get('host') + msg.req.originalUrl
      }
      msg.payload = "";
      return [null, msg]
    } else {
      return [msg, null]
    }
    

    如果你把它放在一个有 2 个输出的函数节点中,它会将重定向发送到第二个输出,否则将它发送到第一个输出。

    您也可以通过在settings.js 中添加自己的httpNodeMiddleware 函数来做到这一点,如下所示:

    ....
    httpNodeMiddleware: function(req, res, next){
      if (req.headers['x-forwarded-proto'] == 'http') {
         res.redirect(301, 'https://' + req.get('host') + req.originalUrl);
      } else {
        next();
      }
    },
    ...
    

    此方法意味着您的流程中不需要任何重定向逻辑

    旁注: 您可能需要测试msg.req.headers['$wssc'] 而不是msg.req.headers.$wssc

    【讨论】:

    • 您的两个建议对我来说都很好。我将在我的应用程序中使用将 httpNodeMiddleware 添加到 bluemix-settings.js,因为它会影响节点中的所有 http。对于您的旁注,我测试了这两个选项并且都有效。谢谢。
    • 可悲的是,这似乎不再起作用了。在将 httpNodeMiddleware 添加到 bluemix-settings.js 并重新启动 Node-RED 之后,我仍然可以通过 HTTP 访问内容。 - 知道如何解决这个问题吗?
    猜你喜欢
    • 2018-11-11
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多