Ruby-on-rails 让 Rails URL helper 自动输出 https url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6699881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:36:05  来源:igfitidea点击:

Getting Rails URL helpers to automatically output https urls

ruby-on-railsrubysslroutes

提问by Joe Van Dyk

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?

我正在开发一个混合了 http 和 https 的网站 - 使链接使用正确的路由协议的最佳/最简单的方法是什么 - 可以在路由文件中指定吗?

Say I have the following route in Rails 3.

假设我在 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/testinstead.

如果我在 http 页面上,并且我使用test_url(),它将输出http://domain.com/test。我想要https://domain.com/test代替。

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

我知道我可以使用test_url(:secure => true),但这是重复的逻辑。

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

我知道我可以有http://domain.com/testhttps://domain.com/test,但这是一个额外的重定向,而且它在表单帖子上失败。

Ideas?

想法?

采纳答案by Joe Van Dyk

回答by Krishna Srihari

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

使用test_url(:protocol => 'https')了HTTPS URL中。

回答by apneadiving

Haven't tried but add this in your ApplicationController:

还没试过,但在你的ApplicationController

def default_url_options(options={})
 { :secure => true }
end 

回答by i_emmanuel

def default_url_options(options={})
 { :protocol => "https" }
end

回答by Mark Ellul

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

对于 Rails 3.2,我结合使用了@apneadiving 的答案。将以下代码添加到我的ApplicationController

def default_url_options(options={})
  options.merge{ :protocol => "https" }
end

回答by Joe Van Dyk

Rails 3 SSL routing redirects from https to httpanswers 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

Rails 3 SSL 路由从 https 重定向到 http很好地回答了这个问题。简而言之,没有什么好的方法可以做到。我提交了以下 Rails 错误:https: //github.com/rails/rails/issues/3571

回答by Ross

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

您可以使用一个名为 ss_requirement 的插件,它会为您提供诸如 ssl_required ssl_allowed 之类的方法

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

您可以简单地将其添加到您的控制器中以启用或禁用任何操作的 https

ssl_allowed :login, :update_profile

https://github.com/rails/ssl_requirement

https://github.com/rails/ssl_requirement