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?
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' }
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With