htaccess - display cached html version

Posted: July 9th, 2008 | Author: sofia | Filed under: performance, scalability, useful | Tags: , | No Comments »

There are several caching strategies in web application development:

  • database caching
  • fragment caching - parts of the rendered output are cached.
  • page caching - the whole output is cached. Useful when the page requires no authentication and has no personalization (eg. no Hello John if he’s logged in).

Page caching is the fastest method since the webserver can serve the html page directly allowing for the web app to be totally bypassed.

The idea is if a page is cached then the webserver detects that it exists in the cache folder and displays it, if the page doesn’t exist then the request continues to the web application which will render the page and save it to cache.

So how can the webserver detect this? Well, modrewrite to the rescue :=)

Here’s the snippet that makes it all possible:
[code]

IndexIgnore *
DirectoryIndex index.php index.html
Options +FollowSymLinks

RewriteEngine On

#if the request is domain.com/about, it will check if domain.com/cachehtml/about.html exists, if so displays it
RewriteCond %{DOCUMENT_ROOT}/cachehtml/$1.html -f
RewriteRule ^([a-z_-]+)$ cachehtml/$1.html [NC,QSA,L]

#goes one level deep
#if the request is domain.com/blog/hello-world, it will check if domain.com/cachehtml/blog/hello-world.html exists, if so displays it
RewriteCond %{DOCUMENT_ROOT}/cachehtml/$1/$2.html -f
RewriteRule ^([a-z_-]+)/([a-z_-]+)$ cachehtml/$1/$2.html [NC,QSA,L]

[/code]

The code above implies we are at the root. If not just add the folder name so that
RewriteCond %{DOCUMENT_ROOT}/cachehtml/$1.html -f
becomes
RewriteCond %{DOCUMENT_ROOT}/mysite/cachehtml/$1.html -f