首页 文章

用于Javascript WebSocket客户端的nginx代理

提问于
浏览
1

我在localhost上运行nginx,提供静态html / css / js文件 . 它代理远程服务器以获取所需的RESTful数据库服务 . 我还需要设置nginx代理到远程websocket服务器,但是对所有尝试都失败了 .

如果我像这样对websocket服务器url进行硬编码,则Javascript客户端可以工作:

socket = new WebSocket("ws://50.29.123.83:9030/something/socket");

显然,不是最佳解决方案,我应该能够使用location.host和代理来到同一个位置 . 我用以下内容配置了nginx:

http {
  ...
  upstream websocket {
    server 50.29.123.83:9030;
    }
}

sever {
  ...
  location /the_socket/ {
        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
  }
}

然后将客户端代码更新为:

socket = new WebSocket("ws://" + location.host + "/the_socket/something/socket");

此操作失败,并显示以下错误:

与'ws:// localhost / the_socket / something / socket'的WebSocket连接失败:WebSocket握手期间出错:意外响应代码:404

我究竟做错了什么?

  • 改变了IP和端口号以保护无辜者

1 回答

  • 1

    您的代理语句将URI未经修改地传递给上游服务器 . 也就是说,文本 /the_socket 仍将附加到URI的开头 .

    如果您希望 proxy_pass 修改URI并删除 location 值 - 您应该在 proxy_pass 语句中添加URI . 例如:

    location /the_socket/ {
        proxy_pass http://websocket/;
        ...
    }
    

    有关详细信息,请参阅this document .

相关问题