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.

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Great, was looking for this and will definitely try this one.
Helped me a lot - didn't think turning ProxyRequests to off would do the trick, but that ended up being the case. Thanks!
7

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

<VirtualHost *>
    ServerName example.org
    ServerAlias *.example.org
    ServerAdmin [email protected]
    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>

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.