SSL in Ruby on Rails
Cristiano - July 09, 2015
Using SSL in Rails is very simple. Assuming that you installed a valid SSL certificate on your production server or on your PaaS Provider (Heroku), it is very easy to switch all links to https. If you want to force every link to https, just add this line to your production.rb
config.force_ssl = true
This is a good way to deliver the whole app over https. If you are writing an application where security is mandatory, this is the way to go. Otherwise it is better to use https only for certain actions.
There are many reasons why one should not publish all the pages with https, the speed of loading is one of them. Usually the SSL Handshake between Server and Browser takes 50 to 100 ms. But in a bad case it can take 600 ms. That is a big performance issue.
Enabling https only for certain pages is better. For example for Registration Pages, Login Pages and Settings Pages. That can be achieved very easily by adding this line to the controller.
It is like a filter. You can customize it with
class SessionsController < ApplicationController force_ssl only: [:new, :create] def new @title = "Sign in" end end
This will force just certain links to https. If you want to switch back to regular http, you can use this filter here:
def force_http if request.ssl? && Rails.env.production? redirect_to protocol: 'http://', status: :moved_permanently end end
Just add it to a controller like this:
If you have forced everything to https before and afterwards you decide to force some pages to http, then you can run in an recursive redirect issue. The browser remembers that the pages are just available via https, but your server is redirecting to http. If you get this issue you have to clear your browser cache.