How to conditionally force SSL depending on domain name?

Add some configuration to your ApplicationController:

class ApplicationController < ActionController::Base
   force_ssl if: :ssl_required?

   [...]

   private
   def ssl_required?
     request.host == 'app.example.com'
   end
end

Source: http://api.rubyonrails.org/classes/ActionController/ForceSSL/ClassMethods.html


In Rails 5 and later you can and should do this via ssh_options because force_ssl is deprecated in controllers from Rails 6.0 and will be removed in 6.1.

config.force_ssl = true
config.ssl_options = {
  redirect: {
    exclude: ->(request) { request.host == 'app.example.com' }
  }
}