【问题标题】:Error during WebSocket handshake: Unexpected response code: 301WebSocket 握手期间出错:意外的响应代码:301
【发布时间】:2019-01-19 00:04:51
【问题描述】:

我已经研究了RoR 5.0.0 ActionCable wss WebSocket handshake: Unexpected response code: 301 的答案,但不适用于我的情况。

我使用 nginx-proxy 作为在 docker-containers 中运行的多个 Web 服务器的前端。我使用来自https://github.com/jwilder/nginx-proxy的 nginx-config-template

现在在我的 docker-container 中,我有另一个 nginx,其配置如下:

map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}

upstream websocket {
    server my-websocket-docker-container:8080;
}

server {
    root /src/html;


    location /websocket/ {
        resolver 127.0.0.11 ipv6=off;
        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }

    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }

    ...

}

当尝试连接到 wss://example.com/websocket 时,我收到上述关于意外响应代码 301 的错误。当我手动 curl websocket-url 时,我可以看到 nginx 响应告诉我“301 永久移动”。但为什么?这是哪里来的?

有人可以帮忙吗?谢谢!

【问题讨论】:

  • 您的location /websocket/ 有一个尾随/,但您连接到/websocket 时没有尾随/。更改任何一个都可能会删除重定向。
  • 是的,非常感谢! :-)
  • 在我问这个问题之前,我当然尝试添加斜杠,但当时我遇到另一个错误,导致超时 504。哦,周末……
  • 如果您想将其作为常规答案发布,我会很乐意支持并接受您的解决方案。谢谢您的帮助! :-)
  • @RichardSmith:你是个摇滚明星。谢谢,就是这样。

标签: nginx websocket nginx-reverse-proxy


【解决方案1】:

我今天遇到了类似的问题。我使用“经典”WebSocket API 和 NGINX 来测试某些服务之间的连接。我想出了以下解决方案:

WebSocket 实例创建:

const websocket = new WebSocket('ws://' + window.location.host + '/path');

Nginx 配置:

location /path {
    proxy_pass http://websocket:port;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

地点:

  1. path是要重定向的路径
  2. websocket 是主机名或主机的IP
  3. port 是主机上提供应用程序的端口

【讨论】:

  • 使用 TLS 时,不要忘记将协议更改为 wss:// 而不是 ws://。归功于nice answer
猜你喜欢
  • 2014-05-15
  • 1970-01-01
  • 2018-01-21
  • 2016-02-02
  • 2017-01-30
  • 2019-11-26
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多