Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force SSL for specific routes in Rails 3.1

I need to force SSL on all routes in my application except for landing#index.

In config/application.rb, I have:

config.force_ssl = true

Then in landing_controller.rb, I have:

force_ssl :except => :index

However, all routes are still being redirected to https.

Does anyone know how to conditionally force SSL in a Rails 3.1+ application?

Solution:

Add the following to your Gemfile:

gem 'rack-ssl-enforcer'

Add the following to your config/application.rb:

config.middleware.use Rack::SslEnforcer, :except => [ /\/$/ ], :strict => true
like image 304
Graham Swan Avatar asked May 15 '12 16:05

Graham Swan


2 Answers

I asked a similar question on stackoverflow here and was told to use https://github.com/tobmatth/rack-ssl-enforcer. I haven't tried it out yet, but based on the readme, it appears to solve your problem of conditionally enforcing ssl on certain routes.

like image 176
anshumans Avatar answered Nov 20 '22 22:11

anshumans


Rails 4 with ActiveAdmin 1.0b, I modified config/initializers/active_admin.rb:

config.before_filter :force_ssl_redirect, if: :https_enabled?

force_ssl_redirect is defined in actionpack/lib/action_controller/metal/force_ssl.rb and is what Rails' force_ssl class method calls.

https_enabled? defined in my application_controller.rb:

def https_enabled?
  ENV['HTTPS_ENABLED'] == 'true'
end
like image 6
Luke W Avatar answered Nov 20 '22 22:11

Luke W