Today I spent some time implementing caching in a Rails application that makes use of subdomains.
With a quick bit of google-fu, I stumbled upon Nathaniel Bibler’s post.
A very informative guide, however, the apache rewrite rules proved to be a bit more involved. In addition, the shennagans of the subdomain seemed a little unnecessary, so I opted for host instead of subdomain. The changes are below.
class ApplicationController < ActionController::Base
private
def cache_page_with_host(content = nil, options = nil)
path = case options
when Hash
url_for(options.merge(:only_path => true, :skip_relative_url_root => true, :format => params[:format]))
when String
options
else
request.path
end
cache_page_without_host(content, File.join("/#{request.host}/", path == "/" ? 'index.html' : path))
end
end
Apache Config
RewriteEngine On
# Rewrite rule to check for host cached pages.
# This will check the file system for a cached copy, if that exists
# use the static cached page.
# The [QSA,L] is very important. See http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriteflags
RewriteCond %{DOCUMENT_ROOT}/cache/%{HTTP_HOST}/index.html -f
RewriteRule ^/$ /cache/%{HTTP_HOST}/index.html [QSA,L]
RewriteCond %{DOCUMENT_ROOT}/cache/%{HTTP_HOST}/%{REQUEST_URI}.html -f
RewriteRule ^(.*)$ /cache/%{HTTP_HOST}/$1.html [QSA,L]