rails force_ssl 関連
このように書くと https に強制される。
config/environments/production.rb
config.force_ssl = true
コントローラ個別に設定したい場合には、上記のように環境ごとのファイルには記載せず、よくこんな風にする。
class SampleController < ApplicationController
force_ssl if: :ssl_configured?
def index
end
end
class ApplicationController < ActionController::Base
private
def ssl_configured?
!Rails.env.development?
end
end
テストでも HTTPS としてアクセスする必要があるのでこの点は注意。
describe SampleController, :type => :controller do
before do
request.env["HTTPS"] = "on"
end
describe "foobar" do
end
end
上では request.env["HTTPS"] = "on" としているが、どういうときに ssl request なのか? というのは、こちらの記事が詳しかった。
if @env[HTTPS] == 'on'
'https'
elsif @env[HTTP_X_FORWARDED_SSL] == 'on'
'https'
elsif @env[HTTP_X_FORWARDED_SCHEME]
@env[HTTP_X_FORWARDED_SCHEME]
elsif @env[HTTP_X_FORWARDED_PROTO]
@env[HTTP_X_FORWARDED_PROTO].split(',')[0]
else
@env["rack.url_scheme"]
end