在客户端,我正在尝试建立wss连接:
var ws = new WebSocket("wss://wsserver.com/test")
它返回一个错误:
WebSocket connection to 'wss://wsserver.com/test' failed: Error during WebSocket handshake: Unexpected response code: 400
完整的 header 是:

请求 header

GET wss://wsserver.com/test HTTP/1.1
Host: wsserver.com
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: https://website.net
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8
Sec-WebSocket-Key: Tj9AJ5TKglNf5LoHsQTpvQ==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

响应标题
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:https://website.net
Connection:close
Content-Length:18
Content-Type:text/plain; charset=utf-8
Date:Fri, 21 Apr 2017 21:03:45 GMT
Server:Apache/2.4.18 (Ubuntu)
Vary:Origin
X-Content-Type-Options:nosniff

服务器端在Apache反向代理后面的端口8888上运行。这是Apache配置:
<VirtualHost *:443>
        ServerName website.com

        ProxyPreserveHost On
        ProxyRequests Off
        ProxyPass "/" "wss://localhost:8888/"

已安装mod_proxy和mod_proxy_wstunnel。

这里缺少什么吗?似乎请求已通过,但未建立连接。

最佳答案

我最终通过对虚拟主机使用此配置解决了此问题,该配置使用HTTP header 过滤请求:

<VirtualHost *:443>
    ServerName website.com

    RewriteEngine On

    # When Upgrade:websocket header is present, redirect to ws
    # Using NC flag (case-insensitive) as some browsers will pass Websocket
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule ^/ws/(.*)    wss://localhost:8888/ws/$1 [P,L]

    # All other requests go to http
    ProxyPass "/" "http://localhost:8888/"

我将其作为引用,以防它对其他人有帮助

关于apache - WebSocket通过SSL与Apache反向代理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43552164/

10-16 13:48