Mongrel Rails + mod_proxy + mod_rewrite configuration for caching
Now that the Adamantine Arts site is getting more traffic, I wanted to implement page caching to really speed things up and prevent excessive server load. I’ll discuss page caching in Rails in more detail at another time. The problem at hand however was to get apache, mongrel, mod_proxy, and mod_rewrite to all play nice together.
My initial stabs at the problem gave me all sorts of grief. My cache setup is odd since I am using subdomains. The default Rails setup, I believe, just cashes the files in the RAILS_ROOT/public folder and lets apache serve up the static files as normal. However, the index for the main site is different for the subdomains (artist pages). i.e. http://adamantinearts.org/ and http://blainegarrett.adamantinearts.org should not serve up the same cached page. This was actually the least of my problems. More so was matching the files and serving them up without hitting mongrel.
After a bit of searching, I found this setup. This didn’t work for me.
Here is the important part of my setup from my httpd.conf virtual host record
...
RewriteEngine On
ProxyRequests Off
ProxyPassReverse / http://localhost:3000/
ProxyPreserveHost Off
#Alias the caches folder
Alias /caches/ /home/clients/adamantinearts.org/web/public/caches/
#Catch all (non root index) files that exist in the filesystem (-f) and rewrite to the cached version
RewriteCond /home/clients/adamantinearts.org/web/public/caches/%{HTTP_HOST}%{REQUEST_FILENAME}.html -f
RewriteRule "^/(.*)" "/caches/%{HTTP_HOST}%{REQUEST_FILENAME}.html"
#Catch the root index if it exist in the filesystem (-f) and rewrite to the cached version
RewriteCond /home/clients/adamantinearts.org/web/public/caches/%{HTTP_HOST}/index.html -f
RewriteRule "^/$" "/caches/%{HTTP_HOST}/index.html"
# Send everything else to the proxy
RewriteCond /home/clients/adamantinearts.org/web/public/caches/%{HTTP_HOST}%{REQUEST_FILENAME}.html !-f
RewriteRule "^/(.*)" "http://localhost:3000/$1" [P,QSA,L]
There might be a better way to do this, but I spent a good portion of my Saturday morning playing with this and if it works, don’t fix it. I hope this helps someone else!
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.


[...] This is dependent on your server setup, but I wrote an article on getting this to work with apache/modproxy/modrewrite. Your rewrite rules will look something like those used in that [...]