[Ruby on Rails] 常に HTTPS 接続する設定は config.force_ssl = true

Ruby on Rails にて、常に HTTPS/SSL 接続する設定方法をご紹介します。

Ruby on Rails | ルビーオンレイルズ

HTTPS/SSL を有効にする

config/environments ディレクトリ以下に環境名毎にファイルがあるので、SSL を有効にしたい環境のファイルを編集します。

ls -l config/environments
total 24
-rw-r--r--  1 username  staff   1.9K  8 19 10:45 development.rb
-rw-r--r--  1 username  staff   3.8K  8 30 00:26 production.rb
-rw-r--r--  1 username  staff   1.7K  8 19 10:45 test.rb

今回は以下のような要件で進めていきます。

  • development 環境では SSL を有効にせず HTTP のまま接続させたい
  • production 環境では、常時 SSL を有効にして HTTPS 接続させたい

config/environments/production.rb を以下のように config.force_ssl = true のコメントアウトを解除するだけで常時 SSL 設定は完了です。

diff --git a/config/environments/production.rb b/config/environments/production.rb
index 21e3919..7619814 100644
--- a/config/environments/production.rb
+++ b/config/environments/production.rb
@@ -49,7 +49,7 @@ Rails.application.configure do
 
 
   # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
-  # config.force_ssl = true
+  config.force_ssl = true

以上、Ruby on Rails で常に HTTPS/SSL 接続させたい、現場からお送りしました。