nginx conf with alternate cache dir

Its a good idea to use an alternate cache directory in rails (in your environment.rb):

config.action_controller.page_cache_directory = RAILS_ROOT + "/public/cache/"

This makes it easier to sweep. To setup nginx to pick up from a rails alternate cache directory like public/cache, I used:

if ($http_user_agent ~* "(iPhone|iPod)") {
  rewrite ^/$ /iphone break;
  proxy_pass http://mongrel-pt;
  break;
}
 
if (-f $request_filename) {
  break;
}
 
if (-f $document_root/cache/$uri/index.html) {
  rewrite (.*) /cache/$1/index.html break;
}
 
if (-f $document_root/cache/$uri.html) {
  rewrite (.*) /cache/$1.html break;
}
 
if (-f $document_root/cache/$uri) {
  rewrite (.*) /cache/$1 break;
}
 
if (!-f $request_filename) {
  proxy_pass http://mongrel-pt;
  break;
}

It was a little tricky to figure out to use the $uri variable. The first rewrite is used for iphone requests so it doesn’t get the non-iphone cached page.

Tags: , ,

3 Responses to “nginx conf with alternate cache dir”

  1. bryanl Says:

    good stuff. this goes in the bookmarks as "useful"

  2. Philip (flip) Kromer Says:

    Super helpful!

    I put up a pastie about how to move the page cache under nginx along with setting sane permissions, etc on the directories:
    http://pastie.caboo.se/145152

  3. Bernard Says:

    Thank you for this post. What will be the rewrite rules if you have dynamic css being cached by your rails application to the public/cache folder as well.