Simple Rack Application on nginx

I took me quite some time to scour the internet for some reliable examples on how to configure nginx to run a simple rack application. There are a lot of resources, but none seem to be well tested and did not suit my needs. The nginx wiki is probably one of the most reliable sources, and the example is based on the information provided there.


# nginx.conf

upstream unicorn_your_site {
  server unix:/tmp/unicorn_your_site.sock fail_timeout=0;
}

server {
  listen 80;
  server_name www.your-site.com;
  rewrite ^/(.*) http://your-site.com permanent;
}

server {
  listen 80;
  server_name your-site.com;

  access_log /srv/www/your-site.com/current/log/access_nginx.log;
  error_log /srv/www/your-site.com/current/log/error_nginx.log;

  root /srv/www/your-site.com/current/public;

  location ~ (\.(php|jar)$)|php[mM]y[aA]dmin {
    deny all;
  }

  try_files $uri/index.html $uri @unicorn_your_site;

  location @unicorn_your_site {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://unicorn_your_site;
  }
}

The example is using unicorn as the upstream server. The first server section reroutes requests for www to the domain. Then locations for the logs and the root of your application are defined. Also, we drop the typical php and jar requests without routing them further. You can turn logging off with access_log off; within any location block if you so desire.

The try_files is where we tell nginx in which order to look for files, of which the last entry directs to our unicorn server.

blog comments powered by Disqus