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.

4
  • possible duplicate of Force SSL using ssl_requirement in Rails app Commented Feb 21, 2011 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. Commented Feb 21, 2011 at 11:42
  • When I try to use ForceSSL solution, it crashes the app on Heroku. Commented Feb 21, 2011 at 12:06
  • @Zimbabao's comment is correct. You're ALWAYS redirecting to https, even when you're already on https! Commented Feb 27, 2014 at 13:51

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

5

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

Otherwise, you can use Rack::SSL.

2 Comments

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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.