Getting Rails URL helpers to automatically output https urls
Solution 1
It looks like this will be solved in Rails 4! https://github.com/rails/rails/commit/9b4514c3b8ecfbc40a44dbd4c2ebd4ce67f4a459
Solution 2
Use test_url(:protocol => 'https')
for https urls.
Solution 3
Haven't tried but add this in your ApplicationController
:
def default_url_options(options={})
{ :secure => true }
end
Solution 4
def default_url_options(options={})
{ :protocol => "https" }
end
Solution 5
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
Joe Van Dyk
Updated on September 17, 2021Comments
-
Joe Van Dyk over 2 years
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?
-
Joe Van Dyk almost 13 yearsThis is a site that mixes http and https a lot though, I think that would make all the URLs https (right?)
-
apneadiving almost 13 yearsyes, you're right, so you should only put this in the controllers having https
-
Joe Van Dyk almost 13 yearsStill not sure how that helps me. If I'm on a http page, I want test_url() to return a https URL, not a http one.
-
apneadiving almost 13 yearsok, sorry about that. Remark: giving -1 to people trying to help you won't serve your cause.
-
Joe Van Dyk over 12 yearsThat doesn't have anything to do with generating URLs.
-
Ross over 12 yearsIn this case you generate your urls as normal, but its is submitted as SSL for the methods that you have mentioned
-
Joe Van Dyk over 12 yearsNo, it's not. It will redirect the http post from http to https, losing the post data.
-
Joe Van Dyk over 11 years"I know I can use test_url(:secure => true), but that's duplicating logic."
-
Toby Speight over 7 yearsAlthough 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.
-
lulalala about 6 yearsProbably things changed, this no longer works in 5.1.4. See stackoverflow.com/a/48781000/474597