Tag Archives: ssl

Adding SSL to a Rails Application

Adding SSL to a new or existing Rails application isn’t really that difficult. If the website exists for a while and you want to move to https, then you must properly redirect (301) visitors to the new url. If it’s a new website, then it’s probably a good idea to use SSL from the start. (it’s must if you collect any kind of sensitive data from the users)

Assumptions : It’s a Rails 4 app, running with nginx, passenger and Ubuntu 14.04 Server. (preferably on VPS, or somehow you should be able to update nginx configs and so). For SSL certificate, I would recommend Comodo PositiveSSL Certificate from NameCheap @ $9 a year, unless you’ve a good reason to spend more on that.

SSL Setup

First, generate a key and then CSR for buying a SSL certificate. Enter the required info as required. Watch out for Common Name / FQDN field, it must match with the domain (in this case : example.com).

openssl genrsa -out example.com.key 2048
openssl req -new -key example.com.key -out example.com.csr

Then copy the content of above csr file to your clipboard (use xclip, a command line utility) and paste that into SSL order form.

xclip -sel clip < path_to_your_csr_directory/example.com.csr

Next, you’ll receive a confirmation email. After confirming that, they will email you the certificate. (usually within few hours)

Once you receive the ssl certificate (usually in *.zip format), extract the zip file (containing certificates) and concatenate them in right order to get a single certificate file.

cat www_example_com.crt COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > ssl-bundle.crt

Now, you need to upload these two files – ssl-bundle.crt and example.com.key (the private key, generated earlier) to the server. (use scp. e.g scp target_file user@server_ip:file_name)

Preparing Rails for SSL

Enable SSL in production mode, by updating the config/environments/production.rb file.

config.force_ssl = true

And you also need to make sure all the external resources (e.g fonts, images, css, js etc) are loaded securely over https only.

Nginx setup

Login to VPS/Server and create/update your nginx config for ssl.

sudo nano /etc/nginx/sites-available/example.com

A sample nginx config for Rails Application.

Now, enable that nginx config and reload the server.

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com
sudo service nginx reload

Update : It’s an old article on setting up SSL for a rails application. Now you don’t even need to buy any Comodo or similar certificates because you can use Lets Encrypt for generating SSL certificates and it’s completely free. Here is an example config on github to help you out.