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

时间:2015-04-22 08:52:59

标签: apache websocket reverse-proxy

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

我找到的所有示例,仅重定向一些路径,例如"< Location /ws> ...。"或" 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已启用。

2 个答案:

答案 0 :(得分:22)

回答自己。

使用RewriteEngine,this post给出的提示和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>

答案 1 :(得分:1)

非常感谢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/$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>