3

I'd like to redirect all site traffic from all controllers to https while in production. Probably using something like the following:

before_filter :redirect_to_https

With the following in the controller:

  def redirect_to_https
    redirect_to :protocol => "https://" unless (request.ssl? || local_request? || Rails.env.development? || Rails.env.staging? ) # probably don't need redundant development with `local_request` present
  end

What is the most effective way to apply this to all controllers vs having to repeat this in each controller?

ylluminate
  • 12,102
  • 17
  • 78
  • 152

1 Answers1

4

Use config.force_ssl = true in your environments/production.rb config file.

If you want a before_filter to apply to all controllers, they all inherit from ApplicationController so put it in there.

DanS
  • 17,550
  • 9
  • 53
  • 47
  • Very good, thanks for that! As for the ApplicationController, I've seen some methods not seemingly inherited by other controllers so I am going to have to look into that further. – ylluminate Apr 07 '12 at 21:27
  • After attempting your suggestion, I'm getting the following: `Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.` Any ideas as to why this would occur? Previously straight https worked fine. – ylluminate Apr 09 '12 at 16:44
  • This means there is an infinite loop somewhere. Did you add any before filters? – DanS Apr 09 '12 at 19:40
  • No additional before filters were added with your suggestion. Interestingly I do get the same error when I remove this line from production.rb and simply add a like before filter on one of the controllers. It seems as though I'm darned if I do and darned if I don't. Hmmm. I'm not seeing anything that should evoke this loop. – ylluminate Apr 10 '12 at 06:45
  • It'll be because of your server configuration. Try searching for 'force_ssl too_many_redirects' http://stackoverflow.com/questions/9267748/force-ssl-causes-never-ending-redirects http://stackoverflow.com/questions/7406749/multiple-redirects-in-rails-when-redirecting-to-https – DanS Apr 10 '12 at 08:57