Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally force SSL depending on domain name?

I have two domain names for my Rails app: app.example.com, short.net. The longer domain is the standard domain and requires HTTPS, the shorter domain is a convenience domain for providing short URLs and requires HTTP.

Currently I am forcing SSL:

config.force_ssl = true

But I really only want to force SSL for the longer domain name. How can I conditionally force SSL depending on domain name? The short domain name will redirect to the main domain name and then be forced to use SSL. This would avoid requiring a SSL certificate for the short domain name.

Thoughts?

like image 465
Joey Avatar asked Mar 13 '14 21:03

Joey


3 Answers

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

like image 125
Jason Noble Avatar answered Oct 05 '22 18:10

Jason Noble


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' }
  }
}
like image 37
Tim Down Avatar answered Oct 05 '22 20:10

Tim Down


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

private

  def force_ssl?
    if Rails.env.production? || Rails.env.staging?
      return request.host != CONFIG[:short_host]
    end
    return false
  end
end
like image 24
Joey Avatar answered Oct 05 '22 18:10

Joey