Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

I have :

  1. Apache 2.4 on port 80 of my server, with mod_proxy and mod_proxy_wstunnel enabled

  2. Node.js + socket.io on port 3001 of the same server

Accessing example.com (with port 80) redirects to 2. thanks to this method with the following Apache configuration:

<VirtualHost *:80>
    ServerName example.com
    ProxyPass / http://localhost:3001/
    ProxyPassReverse / http://localhost:3001/
    ProxyPass / ws://localhost:3001/
    ProxyPassReverse / ws://localhost:3001/
</VirtualHost>

It works for everything, except the websocket part : ws://... are not transmitted like it should by the proxy.

When I access the page on example.com, I have:

Impossible to connect ws://example.com/socket.io/?EIO=3&transport=websocket&sid=n30rqg9AEqZIk5c9AABN.

Question: How to make Apache proxy the WebSockets as well?

like image 631
Basj Avatar asked Oct 21 '22 15:10

Basj


People also ask

Does Apache support WebSockets?

The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.

Can you proxy WebSockets?

WebSocket over a Forward Proxy. WebSocket communication can take successfully take place in the presence of forward proxies, providing the client and proxy server have been configured properly to deal with it.

Do proxies support WebSockets?

Today, most transparent proxy servers will not yet be familiar with the Web Socket protocol and these proxy servers will be unable to support the Web Socket protocol. In the future, however, proxy servers will likely become Web Sockets-aware and able to properly handle and forward WebSocket traffic.

How configure Apache forward proxy?

The client is configured to use the forward proxy to access other sites. When a client want to get the content from the origin server, it sends a request to the proxy naming the origin server as the target. The proxy then requests the content from the origin server and returns it to the client.


1 Answers

I finally managed to do it, thanks to this topic. TODO:

1) Have Apache 2.4 installed (doesn't work with 2.2), and do:

a2enmod proxy
a2enmod proxy_http
a2enmod proxy_wstunnel

2) Have nodejs running on port 3001

3) Do this in the Apache config

<VirtualHost *:80>
  ServerName example.com

  RewriteEngine On
  RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
  RewriteCond %{QUERY_STRING} transport=websocket    [NC]
  RewriteRule /(.*)           ws://localhost:3001/$1 [P,L]

  ProxyPass / http://localhost:3001/
  ProxyPassReverse / http://localhost:3001/
</VirtualHost>

Note: if you have more than one service on the same server that uses websockets, you might want to do this to separate them.

like image 195
Basj Avatar answered Oct 23 '22 05:10

Basj