在所有rails帮助程序中将协议更改为https

Rails 3.1+我希望我的url帮助程序使用https协议,而不必在我调用的每个帮助程序中指定它。 搜索后我发现了各种各样的方法但没有工作,例如:

ROUTES_PROTOCOL = (ENV["RAILS_ENV"] =~ /development/ ? 'http://' : 'https://') scope :protocol => ROUTES_PROTOCOL, :path => "/app" do 

如何才能做到这一点?

所以你想要它主要用于电子邮件中的链接?

我认为这将适用于您的production.rb,development.rb或任何其他环境。

 config.action_mailer.default_url_options = { :host => 'yourwebsite.com', :protocol => 'https' } # Makes it possible to use image_tag in mails config.action_mailer.asset_host = "https://yourwebsite.com" 

如果您使用的是Rails 4,则定义ApplicationController#default_url_options不起作用。 URL选项现在在应用程序的路由配置中定义:

 Rails.application.routes.draw do default_url_options protocol: :https end 

如果要在应用程序上强制使用SSL,可以通过在application.rb (或特定于环境的文件) config.force_ssl设置为true来完成。 有关此主题的更多信息

编辑确定所以我没有找到足够的证据,但我认为你可以覆盖应用程序控制器中的default_url_options=(options={}) ,并在函数体中设置:protocol => :https 。 如果这不是电子邮件的技巧,则必须通过添加config.action_mailer.default_url_options在环境配置中重复此过程。 希望这样做!

在Rails 5.1.4中,我测试了以下场景:

 # in development.rb config.action_controller.default_url_options({:protocol => 'https'}) config.action_controller.default_url_options(:protocol => 'https') # Does not work # in development.rb, outside config block Rails.application.routes.default_url_options[:protocol] = 'https' # Does not work, but works under console # in routes.rb Rails.application.routes.draw do default_url_options protocol: :https # Does not work, but works under console # in ApplicationController def default_url_options(options={}) { secure: true } end # Does not work # in ApplicationController def default_url_options { protocol: :https } end # Works in browser, but does not work under console # in development.rb config.action_controller.default_url_options= {:protocol => 'https'} # Works in browser, but does not work under console 

您可以将此代码添加到ApplicationController

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

您还可以查看Getting Rails URL帮助程序以自动输出https URL

无论您想使用哪种环境ssl(https://),只需将此配置行添加到config/environments配置文件中:

 YOURAPPNAME::Application.configure do # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = true end 

在Rails 3.2.1中,默认情况下force_ssl为true,让我们检查一下

  1. 打开config / environments / production.rb并搜索“config.force_ssl”

config.force_ssl = true – 无需更改

现在在config / environments / development.rb中 – 不需要放置config.force_ssl ,它应该可以工作,因为你的服务器在本地运行。

好的,这是另一种观点

 if !request.ssl? "https://" + request.host + request.request_uri elsif request.ssl? "http://" + request.host + request.request_uri end 

如果是另外的话,在上面的helper基础中添加def,在ActionView :: Helpers中 ,有一个url_for方法,如果你开始使用它,可能会得到你想要的东西。

我尝试了上面的所有答案,只有这对我有用:

配置/环境/ production.rb

 Rails.application.routes.default_url_options[:protocol] = 'https' 

ruby 2.1.4p265(2014-10-27修订版48166)[x86_64-linux] Rails 3.2.22.5