Search code examples
node.jsapachewebsocketreverse-proxymod-proxy

NodeJS + Apache Proxy, having trouble with routing a secured websocket through (apache config help please)


I've looked through countless of posts on here on how to do this, and I wasn't able to get this simple task working. I'm using Apache as a proxy that is suppose to encrypt/decrypt TSL packets, and then have an unsecured communication with the NodeJS server. The problem is that the web application loads fine, however the websocket fails with an error 404 (not found) and I've had an error 200 before (handshaking issue). I've tried many different configurations and it's not working.

This is what I have on the client side.

const connection = new WebSocket('wss://example.com/wss'); 

Using wss:// instead of ws:// here because I want to have a secured connection. On the server side, I have just the standard

ws.on('connection', w => {
    w.on('message', msg => {
        var data = JSON.parse(msg);
        // do something with the message ... 
    });
});

This is my Apache config file

ServerName www.example.com                                                                                                                                                                                                                                                                                                                                                                                                                                                     RewriteEngine on
RewriteCond %{HTTP:Upgrade}=websocket [NC]
RewriteRule /(.*) wss://127.0.0.1:3000/$1 [P,L]

SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
SSLProxyEngine on

ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
ProxyPass /wss ws://127.0.0.1:3000/
ProxyPassReverse /wss ws://127.0.0.1:3000/

On the Apache side I'm not certain if I should have wss:// or ws:// for ProxyPass since it should be insecure between Apache and NodeJS. I put it as ws:// here but both ways didn't work. For this configuration I get 404 error.

Any help would be greatly appreciated! Thanks


Solution

  • I solved this problem with the Nginx reverse proxy,

    The problem is the fact that I set up socket connection to be on the port 8080, but the proxy is set up for the port 3000. The issue should resolve if you put them on the same port.

    i.e. App server,

    const ws = new WebSocket.Server({port: 3001});
    

    Apache

    ProxyPass /wss ws://127.0.0.1:3001/
    ProxyPassReverse /wss ws://127.0.0.1:3001/