39

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
  • 114,565
  • 26
  • 219
  • 213
Joe Van Dyk
  • 6,828
  • 8
  • 57
  • 73

8 Answers8

34

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

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Krishna Srihari
  • 714
  • 6
  • 6
20

Haven't tried but add this in your ApplicationController:

def default_url_options(options={})
 { :secure => true }
end 
Joe Van Dyk
  • 6,828
  • 8
  • 57
  • 73
apneadiving
  • 114,565
  • 26
  • 219
  • 213
7
def default_url_options(options={})
 { :protocol => "https" }
end
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
i_emmanuel
  • 519
  • 6
  • 6
  • 7
    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,906
  • 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,828
  • 8
  • 57
  • 73
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,828
  • 8
  • 57
  • 73
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,562
  • 1
  • 15
  • 26