To complement this interesting article I'd like to point out one more way of implementing a caching system by using mod_rewrite. For this to work we'll need to maintain the following:

1. An index (preferably a database table) of search engine friendly names for all dynamic pages which we wish to cache, for example:

SEF_Index (ID, SEFriendlyName, Type)


- SEFriendlyName is either an automatically generated or manually specified search engine friendly name of the page (e.g. "product-123", "category-7", "article-42", etc.);

- Type indicates the type of the dynamic page which is important for the proper decomposition of SEFriendlyName to a string of commands and parameters (e.g. "product-123" -> "cmd=show_product&pid=123", "category-7" -> "cmd=show_category&catid=7", "article-42" -> "cmd=show_article&artid=42", etc.).

2. Cache Generator Function - a function which stores the dynamic pages as files. This function could be easily implemented if using a template system - it is only necessary to store the parsed HTML template as a file before sending the output to the browser.

3. Cache Controller Function - as already mentioned in this article, we need to implement a function which removes the relevant cache files in response to events that arise within the application. This function could be very simple (e.g. if the site is being updated through a central content management system) or more complicated (e.g. if the pages change in response to multiple user actions).

4. htaccess file with the following entries:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*).html$ index.php?SEFriendlyName=$1 [T=application/x-httpd-php]
The first two lines above check if the requested file name or directory already exists on the server. If the requested file exists, the mod_rewrite rule on the third line will be skipped and the file served as a normal (static) HTML page. Otherwise, the mod_rewrite rule will be applied and the file name (without the ".html" extension) will be passed to the main script, which in turn will generate the dynamic page and store it into the file system.

This method eliminates the need to call a PHP script to check whether the requested page is in the cache. The other methods using a server-side script to check the cache entail reading the cache files and sending them to the web server whereas the described method based on mod_rewrite allows the cached pages to be served straight from the web server.