我正在维护一个 Ruby on Rails 站点,我对如何使用 https 协议(protocol)执行重定向到相对 URL 感到困惑。
我可以使用 http 成功创建到相对 URL 的重定向,例如:
redirect_to "/some_directory/"
但我无法辨别如何使用 https 协议(protocol)创建到 URL 的重定向。我只能通过使用绝对 URLS 来做到这一点,例如:
redirect_to "https://mysite.com/some_directory/"
我想保持我的代码干净,使用相对 URL 似乎是个好主意。有谁知道如何在 Rails 中实现这一点?
最佳答案
ActionController::Base#redirect_to
方法接受一个选项哈希,其中一个参数是 :protocol
它允许您调用:
redirect_to :protocol => 'https://',
:controller => 'some_controller',
:action => 'index'
参见
#redirect_to
的定义和 #url_for
有关选项的更多信息。或者,特别是如果您的所有 Controller 操作都使用 SSL,您可以使用
before_filter
采取更具声明性的方法。 .在 ApplicationController
您可以定义以下方法:def redirect_to_https
redirect_to :protocol => "https://" unless (request.ssl? || request.local?)
end
然后,您可以在具有需要 SSL 的操作的 Controller 中添加过滤器,例如:
class YourController
before_filter :redirect_to_https, :only => ["index", "show"]
end
或者,如果您在整个应用程序中都需要 SSL,请在
ApplicationController
中声明过滤器:class ApplicationController
before_filter :redirect_to_https
end
关于ruby-on-rails - Rails 使用 https 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1662262/