Friday, October 13, 2006

Apache - how to load balance across multiple hosts (using mod_rewrite)

Here is a nice way to load balance requests using Apache and mod_rewrite.

All it takes is a text file with the different targeted servers, and a "load balancer instance" getting the initial requests. This is a nice way to create sticky sessions to different load-balanced back-ends.

RewriteEngine on

RewriteLogLevel 3
RewriteLog /var/opt/logs/rewrite.log

RewriteMap servers rnd:/opt/apache/servers.txt
RewriteRule ^/(.*) https://${servers:mylist}/$1 [R,L]

with servers.txt:
mylist server1.mydomain.com|server2.mydomain.com|server3.mydomain.com