在Rails 3.1中强制SSL用于特定路由

时间:2012-05-15 16:52:40

标签: ruby-on-rails ruby ssl ruby-on-rails-3.1

我需要在我的应用程序中强制使用SSL 所有路径landing#index除外。

config/application.rb中,我有:

config.force_ssl = true

然后在landing_controller.rb,我有:

force_ssl :except => :index

但是,所有路线仍然被重定向到https

有人知道如何在Rails 3.1+应用程序中有条件地强制使用SSL吗?

解决方案:

将以下内容添加到Gemfile

gem 'rack-ssl-enforcer'

将以下内容添加到config/application.rb

config.middleware.use Rack::SslEnforcer, :except => [ /\/$/ ], :strict => true

3 个答案:

答案 0 :(得分:13)

我在stackoverflow here上问了一个类似的问题,并被告知要使用https://github.com/tobmatth/rack-ssl-enforcer。我还没有尝试过,但基于自述文件,它似乎解决了在某些路线上有条件地执行ssl的问题。

答案 1 :(得分:6)

使用ActiveAdmin 1.0b的Rails 4,我修改了config / initializers / active_admin.rb:

config.before_filter :force_ssl_redirect, if: :https_enabled?

force_ssl_redirect在actionpack / lib / action_controller / metal / force_ssl.rb中定义,是Rails' force_ssl类方法调用。

我的application_controller.rb中定义了

https_enabled?

def https_enabled?
  ENV['HTTPS_ENABLED'] == 'true'
end

答案 2 :(得分:-2)

你可以这样做:

<强>控制器

force_ssl :except => :index

查看

假设您的索引路径名称为 index_landing_path

<%= link_to 'Landing', index_landing_path, :protocol => 'http' %>