Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Last active April 19, 2023 11:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drmalex07/6382c99200ec76ec052910021d1ad7ae to your computer and use it in GitHub Desktop.
Save drmalex07/6382c99200ec76ec052910021d1ad7ae to your computer and use it in GitHub Desktop.
Setup apache as a load balancer with sticky sessions. #apache #balancer #stickysession

Readme

We need to enable at least the following modules: headers, env, proxy, proxy_http, proxy_balancer. If we are proxying over AJP of course we should also enable proxy_ajp.

The following is a sample configuration for a site acting as a balancer to 2 instances of a backend application:

<IfModule mod_ssl.c>
    <VirtualHost 192.168.1.6:443>
        ServerAdmin webmaster@localhost
        ServerName helloworld.localdomain

        DocumentRoot /var/www/html/helloworld.localdomain

        ErrorLog "${APACHE_LOG_DIR}/error-helloworld-localdomain.log"
        CustomLog "${APACHE_LOG_DIR}/access-helloworld-localdomain.log" combined

        SSLEngine on
        SSLCertificateFile  /etc/apache2/certs/helloworld-localdomain/server.crt
        SSLCertificateKeyFile /etc/apache2/certs/helloworld-localdomain/server.key

        ProxyTimeout 1800
        ProxyPreserveHost off   

        RequestHeader set X-Forwarded-Proto https
        RequestHeader set X-Forwarded-Port 443
        
        # This Set-Cookie header will always create a sticky session at the balancer (regardless of the 
        # session cookie of the backend application)
        Header add Set-Cookie "route=.%{BALANCER_WORKER_ROUTE}e; path=/foobar/" env=BALANCER_ROUTE_CHANGED     
        <Proxy "balancer://foobar/">
           BalancerMember "http://127.0.0.1:10080/foobar/" route=1
           BalancerMember "http://127.0.0.1:10081/foobar/" route=2
           ProxySet stickysession=route
        </Proxy>
        ProxyPass        "/foobar/" "balancer://foobar/"
        ProxyPassReverse "/foobar/" "balancer://foobar/"

        <FilesMatch "\.(cgi|shtml|phtml|php)$">
                SSLOptions +StdEnvVars
        </FilesMatch>
        <Directory /usr/lib/cgi-bin>
                SSLOptions +StdEnvVars
        </Directory>
        BrowserMatch "MSIE [2-6]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
        BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
    </VirtualHost>
</IfModule>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment