Bri*_*ous 28 https redirect ruby-on-rails relative-path
我正在维护Ruby on Rails站点,我对如何使用https协议重定向到相对URL感到困惑.
我可以使用http成功创建重定向到相对URL,例如:
redirect_to "/some_directory/"
Run Code Online (Sandbox Code Playgroud)
但我无法辨别如何使用https协议创建重定向到URL.我只能通过使用绝对URL来实现,例如:
redirect_to "https://mysite.com/some_directory/"
Run Code Online (Sandbox Code Playgroud)
我想保持我的代码干净,使用相对URL似乎是个好主意.有谁知道如何在Rails中实现这一目标?
Oll*_*lly 37
该ActionController::Base#redirect_to方法采用一个选项哈希,其中一个参数:protocol允许您调用:
redirect_to :protocol => 'https://',
:controller => 'some_controller',
:action => 'index'
Run Code Online (Sandbox Code Playgroud)
请参阅定义#redirect_to和#url_for有关选项的更多信息.
或者,特别是如果要将SSL用于所有控制器操作,您可以使用a进行更具说明性的方法before_filter.在ApplicationController你可以定义下面的方法:
def redirect_to_https
redirect_to :protocol => "https://" unless (request.ssl? || request.local?)
end
Run Code Online (Sandbox Code Playgroud)
然后,您可以在那些具有需要SSL的操作的控制器中添加过滤器,例如:
class YourController
before_filter :redirect_to_https, :only => ["index", "show"]
end
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要在整个应用中使用SSL,请在ApplicationController以下位置声明过滤器:
class ApplicationController
before_filter :redirect_to_https
end
Run Code Online (Sandbox Code Playgroud)
Mar*_*oij 30
如果您希望通过https提供整个应用程序,那么从Rails 4.0开始,最好的方法是force_ssl在配置文件中启用,如下所示:
# config/environments/production.rb
Rails.application.configure do
# [..]
# Force all access to the app over SSL, use Strict-Transport-Security,
# and use secure cookies.
config.force_ssl = true
end
Run Code Online (Sandbox Code Playgroud)
默认情况下,此选项已存在于config/environments/production.rb新生成的应用程序中,但已注释掉.
正如评论所说,这不仅会重定向到https,还会设置Strict-Transport-Security标头(HSTS)并确保在所有Cookie上设置安全标志.这两项措施都可以提高应用程序的安全性而不会有明显的缺 它使用ActionDispatch:SSL.
HSTS过期设置默认设置为一年,不包括子域,这对大多数应用程序来说可能都很好.您可以使用以下hsts选项进行配置:
config.hsts = {
expires: 1.month.to_i,
subdomains: false,
}
Run Code Online (Sandbox Code Playgroud)
如果您正在运行Rails 3(> = 3.1)或者不想对整个应用程序使用https,那么您可以force_ssl在控制器中使用该方法:
class SecureController < ApplicationController
force_ssl
end
Run Code Online (Sandbox Code Playgroud)
就这样.您可以为每个控制器或您的控制器设置它ApplicationController.您可以使用熟悉的if或unless选项有条件地强制https ; 例如:
# Only when we're not in development or tests
force_ssl unless: -> { Rails.env.in? ['development', 'test'] }
Run Code Online (Sandbox Code Playgroud)
And*_*ell 11
ssl_requirement如果链接或重定向是否使用https,您可能最好不要使用而不关心.使用ssl_requirement,您可以声明哪些操作需要SSL,哪些操作能够使用SSL以及哪些操作不需要使用SSL.
如果您正在重定向到Rails应用程序之外的某个位置,那么将协议指定为Olly建议将起作用.
| 归档时间: |
|
| 查看次数: |
37710 次 |
| 最近记录: |