Using mod_rewrite to serve cached page directly


I seriously consider switching from Rails to Yii, but there is something I used a lot with RoR which seems to be missing. It is the possibility to cache full pages into .html files that Apache can serve directly (that is statically). This results in dramatic performance enhancements.

With RoR, when let us say a cache-enabled page "/posts/42" is first generated, a file is statistically created ("/posts/42.html") so that for the next requests, Apache will check whether this file exists or not. If it exists, Apache serves it directly through mod_rewrite, without even waking up the PHP script. If it does not, the request is forwarded to the PHP script.

Is there a simple way to do this with Yii? I would love this feature to be implemented, but any hint on how to start implementing it myself would be great too!

Thanks a lot,


PS: This is a question about Yii creating these static files, not about Apache config, which is no problem.

I think the implementation is not that hard to achieve. But how would you find out that the cached file is expired?

Rough idea for implementation:

  • Use mod_rewrite as you described, to call index.php if requested file does not exist in /cache/ subfolder

  • Add event handlers to onbeginRequest/onendRequest to capture the output with output buffering

  • Write the file to the right place in /cache/ subfolder and refresh the page so that it’s looked up in /cache again

That’s the only problem. Cache expiration has to be triggered explicitly when the content is modified… For example, when a post is updated or a comment added, the cached file has to be deleted.

In fact, I think implementing all this is quite easy. What I would like to know is how could this be done the Yii way! How would this caching system best fit in?

I will definitely try this!

Thank you both very much!