Improved nginx.conf for Ruby On Rails

Maxim Dounin mdounin at mdounin.ru
Tue Oct 7 01:03:08 MSD 2008


Hello!

On Mon, Oct 06, 2008 at 09:33:36PM +0200, Thomas wrote:

>Who told you the ifs are bad practices? They are here to enable 
>Nginx to directly serve static files.

Me, Igor and many others.  They do unneeded work, including 
unneeded syscalls.  Doing an open() in ngx_http_static_module is 
just enough for anything in this particular case.

>By the way in your case, mongrel will be serving static files, 
>and this is really bad!

No.  All files that exists under root will be served by nginx 
itself.  Only non-existent urls will be proxied to backend.

Take a look at:

     location / {
         error_page  404  = @fallback;
     }

This will instruct nginx to serve static files and installs a 
handler for 404 Not Found errors.  I.e. if file is here - nginx 
will just serve it to client.  If it's not here - it will run 
error_page handler instead.

Normally you write in error_page something like

     error_page  404  /errors/404.html;

to serve "pretty" errors to clients.  But it can do much more.  In 
this particular case we use

     error_page  404 = @fallback;

   - '=' to make sure resulting page will be served with response code 
returned by handler itself, not 404

   - @fallback instead of uri to serve request within context of 
named location @fallback

In it's turn, within @fallback location request will be proxied to 
backend.  And this will happen only if there is no static file 
available.

Some notes:

1. Named locations are relatively new beasts.  They appeared in 
nginx 0.6.6, and there are known issues with them in 0.6.32 
(notably with POST requests, fixed in 0.7.12).  I wouldn't 
recommend using the config in question with stable branch for now 
- at least if you have POST requests.  Try 0.7.* instead. :)

2. As far as I see, the config in question differs from the 
http://wiki.codemongers.com/NginxRubyonRailsMongrel in some 
aspects of it's behaviour.  E.g. the latter one will serve /blah 
request as static if there is /blah.html.  If this behaviour is 
really desired - config should be modified appropriately.  I don't 
think that it's a good practice though.

3. I've been mentioned in the original post, but in fact I've just 
explained how standard fallback technique work and fixed some 
obvious errors.  Don't blame on me if it doesn't work. :)

Maxim Dounin





More information about the nginx mailing list