Rails 3 SSL routing redirects from https to http

If you want all your links to be able to switch between http and https, you have to stop using the _path helper and switch to _url helpers.

After that, using a scope with the protocol parameter forced and protocol constraint makes the urls automatically switch.

routes.rb

scope :protocol => 'https://', :constraints => { :protocol => 'https://' } do
  resources :sessions
end

resources :gizmos

And now in your views:

<%= sessions_url # => https://..../sessions %>
<%= gizmos_url   # => http://..../gizmos %>

Edit

This doesn’t fix urls that go back to http when you are in https. To fix that you need to override url_for.

In any helper

module ApplicationHelper
  def url_for(options = nil)
    if Hash === options
      options[:protocol] ||="http"
    end
    super(options)
  end
end

This will set the protocol to ‘http’ unless it was explicitly set (in routes or when calling the helper).

Leave a Comment