7

I have a Rails 3 app running on Heroku and I also have a SSL installed and working. However, my users can still access the site without the https. How do I make sure that all urls are accessed using https?

Thanks

Edit:

I've tried adding this to application_controller.rb

 before_filter :redirect_to_ssl

  def redirect_to_ssl
      redirect_to url_for params.merge({:protocol => 'https://'})
  end

But I receive a Error 310 (net::ERR_TOO_MANY_REDIRECTS) error.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
donald
  • 23,587
  • 42
  • 142
  • 223
  • possible duplicate of [Force SSL using ssl_requirement in Rails app](http://stackoverflow.com/questions/3861772/force-ssl-using-ssl-requirement-in-rails-app) – Simone Carletti Feb 21 '11 at 11:15
  • 1
    You should check before calling redirect. This is clearly a infinite redirect as you are redirecting always. in filter redirect_to_ssl you should first check if its not https. right?. Above content have a cleaner solution. – Zimbabao Feb 21 '11 at 11:42
  • When I try to use ForceSSL solution, it crashes the app on Heroku. – donald Feb 21 '11 at 12:06
  • @Zimbabao's comment is correct. You're ALWAYS redirecting to https, even when you're already on https! – Emil Ahlbäck Feb 27 '14 at 13:51

3 Answers3

7

you may need to check if you are already using ssl... this works for us.

before_filter :redirect_to_ssl
def redirect_to_ssl
    redirect_to :protocol => "https://" unless (request.ssl?)
end
user693960
  • 141
  • 1
  • 2
6

There is a configuration setting you can use in config/production.rb or application.rb for your production environment.

# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true

This served me well on my Rails app without writing extra code.

Yosep Kim
  • 2,931
  • 22
  • 23
5

Here's an answer I posted to a similar question.

Otherwise, you can use Rack::SSL.

Community
  • 1
  • 1
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • I tried Rack:SSL and worked. However, I want to limit the URL that is redirected. for example: I have myapp.com without certificate and myapp.heroku.com with certificate. I want to redirect to SSL only when it is myapp.heroku.com. thanks – donald Feb 21 '11 at 12:42
  • 1
    Rack::SSL has an `:exclude` option. You'll find it reading the middleware code. It accepts a lambda and if the lambda returns true, Rack::SSL will be skipped. – Simone Carletti Feb 21 '11 at 14:03