【问题标题】:Is it OK to do an https redirect from http?从 http 进行 https 重定向可以吗?
【发布时间】:2018-11-21 07:32:40
【问题描述】:

除了 postgresql 数据库之外,我还有一个使用 node.js 和 socket.io 库的 Web 应用程序。它托管在heroku上。对于 socket.io 库,如果我使用输入为“http://X”的站点地址运行代码,但在尝试“https://X”时不会收到错误消息 为了解决这个错误,如果他们访问 http 版本,我会强制将用户重定向到 https 站点。这是我的代码。

<script>
  if (document.URL.indexOf("https") == -1 && document.URL.indexOf("localhost") == -1)
  {
    window.location.href = document.URL.replace("http", "https");
  }
</script> 

有什么理由说明这是一个坏主意吗?有更好的解决方案吗?任何关于 http 和 https 之间区别的 cmets 将不胜感激。这是我在 http 上运行网站时遇到的错误:

WebSocket connection to 'ws://theland.herokuapp.com/socket.io/?EIO=3&transport=websocket&sid=<not sure if I should share this part of the url...>' failed: Error during WebSocket handshake`: 'Sec-WebSocket-Accept' header is missing

澄清一下,该网站现在可以很好地使用我的解决方案,但我担心我的解决方案是否是“良好做法”。

感谢您的帮助!

【问题讨论】:

  • 我写了一个答案,有帮助吗?

标签: html node.js http https socket.io


【解决方案1】:

在客户端,只包含 Socket.IO 而没有 URL:

<script src="/socket.io/socket.io.js"></script>
<script> const socket = io(); </script>

另一种选择是将 URL 用于:

wss://yourURL

如果这不起作用,更好的方法是从服务器端重定向,例如:

app.get('/anyURL', (req, res) => {

    if (req.headers.host.match(/^www/) !== null || !req.secure) {
        return res.redirect('https://' + req.headers.host.replace(/^www\./, '') + req.url);
    };
});

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2021-09-12
    • 2019-09-10
    • 2017-10-06
    • 2023-03-10
    • 2017-05-28
    • 1970-01-01
    • 2017-11-04
    • 2019-12-17
    相关资源
    最近更新 更多