We recently migrated a Rails application from non SSL to SSL. Before deploying to the staging we obviously wants to test everything locally in development environment. And there is not surprise that enabling SSL in Ruby on Rails development environment is easy. I will show you how we can enable SSL on thin server.

Here are the four simple step to enable SSL locally

  1. Create a self-signed Certificate
  2. Install Thin
  3. Configure the application for HTTPS
  4. Boot Thin

Create a self-signed Certificate

Create .ssl directory in the rails app and create a certificate with name localhost in that directory. This is to make your browser believe the certificate is owned by the localhost domain.

$ mkdir .ssl

$ openssl req -new -newkey rsa:2048 -sha1 -days 365 -nodes -x509 -keyout .ssl/localhost.key -out .ssl/localhost.crt

This will create localhost.crt and localhost.key files in the .ssl directory.

Install Thin

Install thin is super easy. Add thin and remove webrick to your Gemfile file and bundle.

# add this to your gem file
gem ‘thin’

Configure the application for HTTPS

By default the app is configured for HTTP. To serve the application configure the force_ssl option in application.rb which has false as default value.

You can turn this feature on in specific environment (i.e. test, production, and application) by setting the value to true in the environment file. e.g,

# config/environments/production.rb
MyApp::Application.configure do
config.force_ssl = true

Note: Restart the server to apply the change.

To apply the HTTPs across the environments, set force_ssl to true in application.rb.

# config/application.rb
module MyApp
class Application < Rails:: Application
config.force_ssl = true

Once SSL is enabled, the framework will perform the following actions.

  1. All cookies set by the application are flagged as secure
  2. All HTTP request will be redirected to HTTPS

Cool! isn’t it?

Boot Thin server

You need to mention key and certificate path while starting the thin server

$ thin start - ssl - ssl-key-file ~/.ssl/localhost.key - ssl-cert- file ~/.ssl/localhost.crt

One can also start thin with two diffrent port one with non-SSL and another with SSL by using -p. Super cool!

$ thin start -p 3000
$ thin start -p 3001 - ssl - ssl-key-file ~/.ssl/localhost.key - ssl-cert- file ~/.ssl/localhost.crt

That’t it! Thank you for reading.

Click here for more details

At BoTree Technologies, we build enterprise applications with our RoR team of 30+ engineers.

We also specialize in RPA, AI, Python, Django, JavaScript and ReactJS.

Consulting is free – let us help you grow!