Aug 27, 2009

Quick Tip: Page caching and POST in Rails

I've been playing around with Page Caching as inspired by the New Relic screencasts. I managed to get my callbacks in place and although I'm still struggling a bit with the flash messages, things are notably better than they were before I started. One hiccup I ran into though was the fact that page caching was preventing new records from being created in my app. Why? Because when I look for a list of products, the request goes to /products (GET) and when I create a new product the request goes to /products (POST). Apache intercepts both and derails by rails.


The full instructions on page caching that I followed in case anyone is interested are right here. You'll also want to check out those screencasts.

Anyway, to solve it I had to alter the instructions so that POST requests were not cached. In my /etc/apache2/sites-enabled/ directory, I modified my server entry and added these lines:


RailsAllowModRewrite On
RewriteEngine On

RewriteCond %{THE_REQUEST} !^POST
RewriteCond %{REQUEST_URI} ^/([^.]+)$
RewriteCond %{DOCUMENT_ROOT}/cache/%1.html -f
RewriteRule ^/[^.]+$ /cache/%1.html [QSA,L]

RewriteCond %{DOCUMENT_ROOT}/cache/index.html -f
RewriteRule ^/$ /cache/index.html [QSA,L]


This is the one that makes the difference.

RewriteCond %{THE_REQUEST} !^POST


Ideally, I'd set it to cache just the gets but my apache foo isn't quite up to speed for that so telling it to ignore the posts is what I ended up with. Hope this saves somebody else some hair pulling.

No comments:

Post a Comment