17

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.

metalim
  • 1,479
  • 1
  • 12
  • 22

3 Answers3

45

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>
Community
  • 1
  • 1
metalim
  • 1,479
  • 1
  • 12
  • 22
6

Thanks a lot to metalim! I publish the full configuration here for reference:

<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>
Ivan Ermilov
  • 1,769
  • 1
  • 11
  • 10
1

Since Apache httpd 2.4.47, this can be used:

ProxyPass / http://127.0.0.1:3000/ upgrade=websocket

https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#protoupgrade

Karel Vlk
  • 230
  • 1
  • 6