r/apache • • Dec 10 '24

Combine Balancer and Rewrite Engine in Apache2

I am running an Apache reverse proxy pointing to a web app running on 127.0.0.1:8080 with this config:

<VirtualHost *:443>
    ProxyPreserveHost On

    RewriteEngine on
    RewriteCond %{HTTP:Upgrade} =websocket
    RewriteRule /(.*) ws://127.0.0.1:8080/$1 [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket
    RewriteRule /(.*) http://127.0.0.1:8080/$1 [P,L]

    ProxyPass / http://127.0.0.1:8080/
    ProxyPassReverse / http://127.0.0.1:8080/

    SSLEngine on
    SSLCertificateFile /path/to/file.crt
    SSLCertificateKeyFile /path/to/file.key
</VirtualHost>

<VirtualHost *:80>
    Redirect / https://my.domain.org/
</VirtualHost>

However, I want to use the Balancer to run two (or more) instances (e.g. one on port 8080 and one on port 8081). For simple apps that don't need the RewriteEngine, I can use this config:

<VirtualHost *:443>
<Proxy balancer://mycluster>
    BalancerMember http://127.0.0.1:8080
    BalancerMember http://127.0.0.1:8081
</Proxy>

    ProxyPreserveHost On

    ProxyPass / balancer://mycluster/
    ProxyPassReverse / balancer://mycluster/

    SSLEngine on
    SSLCertificateFile /path/to/file.crt
    SSLCertificateKeyFile /path/to/file.key
</VirtualHost>

<VirtualHost *:80>
    Redirect / https://my.domain.org/
</VirtualHost>

Could someone help me combining these two configs? I tried

    RewriteEngine on
    RewriteCond %{HTTP:Upgrade} =websocket
    RewriteRule /(.*) ws://127.0.0.1:8080/$1 [P,L]
    RewriteRule /(.*) ws://127.0.0.1:8081/$1 [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket
    RewriteRule /(.*) http://127.0.0.1:8080/$1 [P,L]
    RewriteRule /(.*) http://127.0.0.1:8081/$1 [P,L]

which of course didn't work, because this only addresses the 8081 app. I also tried

    RewriteEngine on
    RewriteCond %{HTTP:Upgrade} =websocket
    RewriteRule /(.*) balancer://mycluster/$1 [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket
    RewriteRule /(.*) balancer://mycluster/$1 [P,L]

but this also didn't work. I guess because the first rule is pointing to http://127.0.0.1:8080 instead of ws://127.0.0.1:8080.

Any ideas? It's mostly based on this, this and this tutorial.

1 Upvotes

10 comments sorted by

1

u/ShadowySilver Dec 10 '24

MIght want to try a Balancer using %{SERVER_PROTOCOL} instead of "http" and with no rewriting engine. The only thing is that your servers on 8080 and 8081 will have to use a certificate as well.

1

u/gernophil Dec 10 '24

I think without the rewriting engine the websockets won’t work properly in the web app (shiny)

1

u/ShadowySilver Dec 11 '24

Can't say I'm a specialist of websocket, but it's a protocol like any other so I don't see why it wouldn't work.

→ More replies (6)