这个问题与SO question and answer (rails-3-ssl-deprecation )有关,它建议在rails 3中使用路由来处理ssl.rb和路由如下:

resources :sessions, :constraints => { :protocol => "https" }

# Redirect /foos and anything starting with /foos/ to https.
match "foos(/*path)", :to => redirect { |_, request|  "https://" + request.host_with_port + request.fullpath }

My problem is that links use relative paths(i think thats the correct term) and once I'm on a https page all the other links to other pages on the site then use https.

1) 对于不需要https的页面,返回http的最佳方式是什么?我是否必须为所有这些设置重定向(我希望注意),还是有更好的方法.重定向是这样的吗:

match "foos(/*path)", :to => redirect { |_, request|  "http://" + request.host_with_port + request.fullpath }

2) 如果需要重定向回http,我该如何处理这样一种情况:除了一个方法之外,我希望所有方法都是http?ie foos(/*路径)适用于所有foos方法.但是我想让foos/upload_foos使用ssl.我知道怎么要求

scope :constraints => { :protocol => "https" } do
  match 'upload_foos' => 'foos#upload_foos', :via => :post, :as => :upload_foos 
end

但是如果我把http重定向放在foos路径上,https上传会发生什么?

推荐答案

如果你想让所有的链接都能在http和https之间切换,你必须停止使用_path助手,切换到_url助手.

之后,使用带有协议参数forced和协议约束的作用域会使URL自动切换.

routes.rb
scope :protocol => 'https://', :constraints => { :protocol => 'https://' } do
  resources :sessions
end

resources :gizmos

现在在你看来:

<%= sessions_url # => https://..../sessions %>
<%= gizmos_url   # => http://..../gizmos %>

编辑

这不会修复在使用https时返回http的URL.要解决这个问题,需要覆盖url_for.

In any helper
module ApplicationHelper
  def url_for(options = nil)
    if Hash === options
      options[:protocol] ||= 'http'
    end
    super(options)
  end
end

这将把协议设置为"http",除非它是显式设置的(在路由中或在调用帮助程序时).

Ruby-on-rails相关问答推荐

Rails 7通过引擎将方法自动加载到控制器中的方法

在Ruby on Rails中获取堆栈级别太深错误(&Q)

我try 使用Ruby on Rails7创建一个Carbon 足迹计算器.但我无法保存和用户S对象

Web控制台不会出现在例外页面Rails 7.1.1上

如何通过graphqlMutations 从rails销毁当前用户会话

为什么是 json.partial!使用新的哈希语法传递本地时,jbuiler 模板中的行不执行?

如何在测试期间为 Rails 应用程序启用 Rails.cache 会话对象

Rails 中的转义值(类似于 mysql_real_escape_string())

如何在 Ruby on Rails 中创建一个锚点并重定向到这个特定的锚点

bundle和gem安装的区别?

如何独立测试模型的回调方法?

如何在不删除项目本身的情况下删除单个 HABTM 关联项目?

Rails Rake 任务 - 访问模型类

Ruby on Rails i18n - 想要在模型中翻译自定义消息

ruby/ruby on rails 内存泄漏检测

如何在两个字段上对 ruby​​/rails 进行排序?

使用 heroku 和 namecheap 设置自定义域

即使X-Frame-Options为ALLOWALL,也无法在 iframe 中显示我的 rails 4 应用程序

如何设置 MiniTest?

默认情况下 haml