相同 URL 上的 Apache2 WebSockets 反向代理

Apache2 WebSockets reverse proxy on same URL

如何配置 Apache2 来代理 WebSocket 连接(例如 BrowserSync),如果它是在同一个 URL 上创建的,唯一的区别是 header "Upgrade: websocket" 和 URL 架构 ws://?

例如:

HTTP request:
GET http://example.com/browser-sync/socket.io/?... HTTP/1.1
...

WebSocket request:
GET ws://example.com/browser-sync/socket.io/?... HTTP/1.1
Connection: upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
...

我找到的所有示例,仅重定向某些路径,例如“...”或 "ProxyPass /ws/ ws://example.com/"

我当前的配置:

ProxyRequests off
<Location />
    ProxyPass http://127.0.0.1:3000/
    ProxyPassReverse /
</Location>

mod_proxy、mod_proxy_http 和 mod_proxy_wstunnel 已启用。

自己回答。

使用 RewriteEngine,this post 给出的提示,以及 WebSocket 握手规范:

RewriteEngine On
RewriteCond %{HTTP:Connection} Upgrade [NC]
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteRule /(.*) ws://127.0.0.1:3000/ [P,L]

ProxyRequests off
<Location />
    ProxyPass http://127.0.0.1:3000/
    ProxyPassReverse /
</Location>

非常感谢metalim!我在这里发布完整的配置以供参考:

<VirtualHost *>
    ServerName example.org
    ServerAlias *.example.org
    ServerAdmin sysadmin@example.org
    ProxyRequests Off
    ProxyPreserveHost On

    RewriteEngine On
    RewriteCond %{HTTP:Connection} Upgrade [NC]
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteRule /(.*) ws://192.168.1.1/  [P,L]

    ProxyPass / http://192.168.1.1/ retry=1
    ProxyPassReverse / http://192.168.1.1/

    ErrorLog /var/log/apache2/example.org.error.log
    CustomLog /var/log/apache2/example.org.access.log combined
</VirtualHost>