[TIP] Enhancement to nginx/mongrel Rails proxy configuration

Ezra Zygmuntowicz ezmobius at gmail.com
Wed Jan 3 21:59:37 MSK 2007


Hey Gang-

	I was just writing a custom rails config with mongrel for a client  
and was having issues with the page caching rewrites to use a custom  
location. So I turned on debug logging. I was stunned to see that all  
requersts, even static images where getting rewritten a few times   
and had multiple regexes run on them that were not necessary. Doh!

	The way rails page cachign works is that our conf does these steps:

       # check for index.html for directory index
       # if its there on the filesystem then rewite
       # the url to add /index.html to the end of it
       # and then break to send it to the next config rules.
       if (-f $request_filename/index.html) {
         rewrite (.*) $1/index.html break;
       }

       # this is the meat of the rails page caching config
       # it adds .html to the end of the url and then checks
       # the filesystem for that file. If it exists, then we
       # rewite the url to have explicit .html on the end
       # and then send it on its way to the next config rule.
       # if there is no file on the fs then it sets all the
       # necessary headers and proxies to our upstream mongrels
       if (-f $request_filename.html) {
         rewrite (.*) $1.html break;
       }

       if (!-f $request_filename) {
         proxy_pass http://mongrel;
         break;
       }
     }

	I realized what was happening was that all requests , even ones for  
static content were getting checked with these rewrites. SO when a  
request for /images/foo.jpg came in the rewites happened in this order:

/images/foo.jpg/index.html # not found continue
/images/foo.jpg.html # not found continue
finally serve /images/foo.jpg

	This is crazy! Every static request is getting hit with two regexes  
and two checks for files on the fs. Suck! So I added this condition  
as the first thing to check:

       # if this request matches a static file just send it out.
       if (-f $request_filename) {
         break;
       }

	Now all static assets get one check and test before they are served.  
This has increased the static throughput significantly in our setup.  
Hope this helps a few other folks.

-- Ezra Zygmuntowicz 
-- Lead Rails Evangelist
-- ez at engineyard.com
-- Engine Yard, Serious Rails Hosting
-- (866) 518-YARD (9273)









More information about the nginx mailing list