Apache2 WebSockets在相同的URL上反向代理

met*_*lim 9 apache reverse-proxy websocket

如何将Apache2配置为代理WebSocket连接(例如BrowserSync),如果它是在同一个URL上进行的,只有区别是标题"Upgrade:websocket"和URL schema 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
...
Run Code Online (Sandbox Code Playgroud)

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

我当前的配置:

ProxyRequests off
<Location />
    ProxyPass http://127.0.0.1:3000/
    ProxyPassReverse /
</Location>
Run Code Online (Sandbox Code Playgroud)

mod_proxy,mod_proxy_http和mod_proxy_wstunnel已启用.

met*_*lim 25

回答自己.

使用RewriteEngine,这篇文章给出的提示和WebSocket握手规范:

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

ProxyRequests off
<Location />
    ProxyPass http://127.0.0.1:3000/
    ProxyPassReverse /
</Location>
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢! (2认同)

小智 6

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

<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/$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>
Run Code Online (Sandbox Code Playgroud)