Search code examples
apachewebsocketreverse-proxy

Apache2 WebSockets reverse proxy on same URL


How to configure Apache2 to proxy WebSocket connection (BrowserSync for example), if it's made on the same URL, with only difference being header "Upgrade: websocket" and URL schema ws://?

For example:

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
...

All examples I find, redirect some path only, like "<Location /ws>..." or "ProxyPass /ws/ ws://example.com/"

My current config:

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

mod_proxy, mod_proxy_http and mod_proxy_wstunnel are enabled.


Solution

  • Answering myself.

    Using RewriteEngine, hint given by this post, and WebSocket handshake specification:

    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>