36

I am developing a site that mixes http and https a lot - whats the best/easiest way to make the links use the right protocol for the route - can it be specified in the routes file?

Say I have the following route in Rails 3.

match "/test" => "test#index", :as => :test, :constraints => { :protocol => 'https' }

If I'm on a http page, and I use test_url(), it'll output http://domain.com/test. I want https://domain.com/test instead.

I know I can use test_url(:secure => true), but that's duplicating logic.

I know I could have http://domain.com/test to https://domain.com/test, but that's an extra redirect, plus it fails on form posts.

Ideas?

apneadiving
  • 112,549
  • 26
  • 215
  • 208
Joe Van Dyk
  • 6,610
  • 7
  • 54
  • 72

8 Answers8

31

Use test_url(:protocol => 'https') for https urls.

Ashish Ahuja
  • 4,913
  • 10
  • 51
  • 65
Krishna Srihari
  • 674
  • 6
  • 6
20

Haven't tried but add this in your ApplicationController:

def default_url_options(options={})
 { :secure => true }
end 
Joe Van Dyk
  • 6,610
  • 7
  • 54
  • 72
apneadiving
  • 112,549
  • 26
  • 215
  • 208
7
def default_url_options(options={})
 { :protocol => "https" }
end
Toby Speight
  • 25,191
  • 47
  • 61
  • 93
i_emmanuel
  • 471
  • 6
  • 5
  • 6
    Although this code may help to solve the problem, it doesn't explain _why_ and/or _how_ it answers the question. Providing this additional context would significantly improve its long-term value. Please [edit] your answer to add explanation, including what limitations and assumptions apply. – Toby Speight Aug 11 '16 at 16:48
4

For Rails 3.2 I used a combination of @apneadiving's answer. Adding the below code to my ApplicationController

def default_url_options(options={})
  options.merge{ :protocol => "https" }
end
Mark Ellul
  • 1,886
  • 3
  • 26
  • 37
2

It looks like this will be solved in Rails 4! https://github.com/rails/rails/commit/9b4514c3b8ecfbc40a44dbd4c2ebd4ce67f4a459

Joe Van Dyk
  • 6,610
  • 7
  • 54
  • 72
1

Rails 3 SSL routing redirects from https to http answers this question pretty well. In short, there's not a great way to do it. I submitted the following Rails bug: https://github.com/rails/rails/issues/3571

Community
  • 1
  • 1
Joe Van Dyk
  • 6,610
  • 7
  • 54
  • 72
0

To generate https url, add an option called protocol with value https

test_url(protocol: 'https')
-1

You can use a plugin called ss_requirement, it will provide you with methods like ssl_required ssl_allowed

You can simply add this in your controller to enable ot disable https on any action

ssl_allowed :login, :update_profile

https://github.com/rails/ssl_requirement

Ross
  • 1,521
  • 1
  • 12
  • 24