本文介绍了Rails 3 SSL 路由从 https 重定向到 http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与这个 SO 问答 (rails-3-ssl-deprecation) 建议在 rails 3 中使用 routes.rb 和如下路由处理 ssl:

This question relates to this SO question and answer (rails-3-ssl-deprecation) where its suggested to handle ssl in rails 3 using routes.rb and routes like:

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 }

我的问题是链接使用相对路径(我认为这是正确的术语),一旦我在 https 页面上,所有其他链接到网站上的其他页面然后使用 https.

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

1) Whats the best way to get back to http for pages where https isn't required? Do I have to setup redirects for all them(I hope note) or is there a better way. Would the redirects be like this:

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

2) 如果需要重定向回 http,我如何处理我希望所有方法都为 http 的情况,除了一个方法?即 foos(/*path) 将用于所有 foos 方法.但是说我想让 foos/upload_foos 使用 ssl.我知道如何要求它

2) If redirects back to http are required, how do I handle a case where I want all methods to be http except one? ie foos(/*path) would be for all foos methods. But say I wanted foos/upload_foos to use ssl. I know how to require it

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

但是如果我将 http 重定向放入 foos 路径,https upload_foos 会发生什么?

but if I put in the http redirect to the foos path what happens to https upload_foos?

推荐答案

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

If you want all your links to be able to switch between http and https, you have to stop using the _path helper and switch to _url helpers.

此后,使用带有协议参数强制和协议约束的作用域会使网址自动切换.

After that, using a scope with the protocol parameter forced and protocol constraint makes the urls automatically switch.

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.

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

除非明确设置(在路由中或调用助手时),否则这会将协议设置为http".

This will set the protocol to 'http' unless it was explicitly set (in routes or when calling the helper).

这篇关于Rails 3 SSL 路由从 https 重定向到 http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 13:55
查看更多