nginx + ssl + rails

While nginx has been covered here before, it seems the blogosphere is a bit lacking in covering a nginx + ssl + rails setup, which requires a little bit of putting 2 and 2 together and getting 5. The configuration is as such:

server {
  listen 443;
  ssl on;
  # path to your certificate
  ssl_certificate /etc/nginx/certs/server.crt; 
  # path to your ssl key
  ssl_certificate_key /etc/nginx/certs/server.key; 

  # put the rest of your server configuration here.

  location / {
     # set X-FORWARDED_PROTO so ssl_requirement plugin works
     proxy_set_header X-FORWARDED_PROTO https;

         # standard rails+mongrel configuration goes here.
  }
}

The kicker is the proxy_set_header line—it is crucial to allowing your Rails app to know whether the request was sent over http or https.

You will note that there is no server_name directive—this is because it is impossible to do name-based virtual hosts when doing https. You must have a separate IP address for each ssl host—you can specify which IP address to use (if your machine has multiple assigned IPs) by modifying the the listen directive, e.g. listen 101.102.103.104:443.

On a related note, here at Agora Games we recently launched our first production site running on nginx and Rails!

Addendum (13 June 2007): It is worth noting that Ezra’s excellent nginx configuration includes an ssl section, although it unfortunately lacks the ssl commands themselves.

Addendum (16 July 2008): My good friend Andrew Loe has put together a post covering all steps necessary to creating a self-signed ssl certificate in OS X and getting it working with Rails and nginx – ideal for your local development environment.