views:

42

answers:

2

I have a Rails application which need to run under SSL. I tried ssl_requirement but seems I have to type in all the actions in every controllers.

Is there any method that I can add a before_filter in application controller with ssl_requirement, so that the apps will redirect to https automatically when user request is in http?

Thanks all. :)

+1  A: 

You can try test if request is in ssl or not in a before_filter in your application

class Application < AC::Base

  before_filter :need_ssl

  def need_ssl
    redirect_to "https://#{request.hosts}:#{request.port}/#{request.query_string}" unless ssl?
  end
end
shingara
oops... i got an error. undefined method `ssl?'
siulamvictor
Maybe your are not in Rails 3 ?
shingara
i am still in rails 2... so this is in rails 3, right?
siulamvictor
+2  A: 

Use a Rack Middleware.

# lib/force_ssl.rb
class ForceSSL
  def initialize(app)
    @app = app
  end

  def call(env)
    if env['HTTPS'] == 'on' || env['HTTP_X_FORWARDED_PROTO'] == 'https'
      @app.call(env)
    else
      req = Rack::Request.new(env)
      [301, { "Location" => req.url.gsub(/^http:/, "https:") }, []]
    end
  end
end

# config/environment.rb
config.middleware.use "ForceSSL"
Simone Carletti
it's working well. thanks mate. :)
siulamvictor