Rails with SSL in Development The Simple Way

Posted by Brian in Rails (July 21st, 2013)

To use SSL with Rails, you could set up Apache on your development machine, but that involves a virtual host and a bunch of other bits of configuration. Here’s a dirt simple way.

  1. Create a self signed certificate
  2. Install Thin
  3. Force SSL in Rails
  4. Add a host entry
  5. Launch with Thin

Create a self-signed certificate

We’re going to create a self-signed certificate for the site localhost.ssl.

In the root of your Rails application, do these commands:

First, generate a simple signing key. You’ll have to enter a passphrase. Enter 1234. We’re going to remove the passphrase in the next step anyway.

openssl genrsa -des3 -out server.orig.key 2048

Now remove the passphrase from the key by converting it to an RSA key:

openssl rsa -in server.orig.key -out server.key

Now create the certificate request. When prompted for the “common name”, be sure to make it localhost.ssl

openssl req -new -key server.key -out server.csr

Now create the self-signed certificate.

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Install Thin

Install Thin by adding this to your Gemfile:

gem 'thin'

Force SSL in Rails

In config/application.rb, find this line:

class Application < Rails::Application

and add this within the class definition:

config.force_ssl = true

Add a Host Entry

Now add a host entry to your system so you can bring up https://localhost.ssl in a web browser. Do this with your favorite text editor, or use the command below to push the new host entry on to the end of your hosts file:

echo " localhost.ssl" | sudo tee -a /private/etc/hosts

Launch app with Thin

Here's the command to launch this app:

thin start --ssl --ssl-verify --ssl-key-file server.key --ssl-cert-file server.crt

You could put that in script/start and then use

chmod +x script/start

to have a simple way to start your app with ./script/start.

Wrapping Up

This is a dirt simple way to set this up and it's a lot less work to use it once you set it up the first time.
If you were working on multiple sites, you would want to create a single key and cert which you could share across all of your apps.