Using mod_rewrite in Apache 2.0 for load balancing

The mod_proxy_balancer function included with Apache 2.2 is a great way to set up an Apache front end to a rails-based Mongrel cluster. The latest versions of many Linux distributions now include Apache 2.2 but unless you have a new server with the latest distro, it’s likely that your server is running Apache 2.0.

I usually try to avoid upgrading from Apache 2.0 to 2.2 by compiling it from source because of all of the interdependencies. You end up having to recompile so much other stuff, that it just turns out to be a mess.

Fortunately Apache 2.0 can use mod_rewrite which can be used to do some primitive random load balancing. Here is a sample configuration snippet:

<VirtualHost>
        ServerName mydomain.com
        ServerAlias www.mydomain.com

        ## The random map file of our clusters
        RewriteMap clusters rnd:/etc/httpd/conf/clusters.map
        RewriteEngine On

        ## Don't rewrite for static files
        RewriteCond %{REQUEST_FILENAME} !-f
        # Use mod_rewrite to randomly select from one of the Mongrel
        # cluster servers
        RewriteRule ^/(.*) http://${clusters:mongrel_cluster}/$1 [P,L]
</VirtualHost>

The cluster.map file should contain something like this:

mongrel_cluster  localhost:3000|localhost:3001|localhost:3002

Obviously, you’ll want to substitute your server names where appropriate, and configure the correct ports for your instances in the map file

Leave a Reply

Your email address will not be published.