ruby-on-rails - 使用 Rails 3.1 的 Heroku 中特定于 SSL 的主机名

标签 ruby-on-rails ruby ssl https hostname

我目前有一个设置,我在我的应用程序 Controller 中使用 before_filter 在需要的地方强制使用 SSL 或 http:

def force_ssl
  if params[:controller] == "sessions"
    if !request.ssl? && Rails.env.production?
      redirect_to :protocol => 'https://', :status => :moved_permanently
    end
  else
    if request.ssl? && Rails.env.production?
      redirect_to :protocol => 'http://', :status => :moved_permanently
    end
  end
end

我想做的是在使用 SSL 时使用 https://secure.example.com 但在使用 SSL 时继续使用 http://example.com不使用 SSL。有没有一种方法可以根据我是否使用 SSL 在主机名之间切换?

最佳答案

首先,我将展示如何在当前和早期版本的 Rails 中强制使用 SSL,然后在最后我发布了如何并行使用 HTTP 和 HTTPS,这正是我认为您正在寻找的。

rails >= 3.1

只需在您的环境配置中使用 config.force_ssl = true

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.force_ssl = true
  end
end

您还可以根据当前的 Rails 环境有选择地启用 https。例如,您可能希望在开发时关闭 HTTPS,并在暂存/生产时启用它。

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.force_ssl = false
  end
end

# config/environments/production.rb
MyApp::Application.configure do
  config.force_ssl = true
end

rails < 3.1

以防万一您有任何不是 Rails 3.1 的项目并且想要相同的功能。通过将以下行添加到您的环境配置来启用 HTTPS。

config.middleware.insert_before ActionDispatch::Static, "Rack::SSL"

请注意,我将 Rack::SSL 作为字符串传递,以委托(delegate)在 Rails 应用程序初始化结束时加载类。另请注意,中间件必须插入堆栈中的特定位置,至少在 ActionDispatch::StaticActionDispatch::Cookies 之前。

不要忘记在 Gemfile 中定义 Rack::SSL 依赖。

# Gemfile
gem 'rack-ssl', :require => 'rack/ssl'

并行启用 HTTPS 和 HTTP

Rack::SSL 有一个非常有趣且未记录的功能。您可以传递 :exclude 选项来确定何时启用/禁用 HTTPS。

以下代码仅在请求来自 HTTPS 连接时启用 Rack::SSL 及其所有过滤器。

config.middleware.insert_before ActionDispatch::Static, Rack::SSL, :exclude => proc { |env| env['HTTPS'] != 'on' }

以下两个 URL 将继续工作,但第一个将触发 Rack::SSL 过滤器。

https://secure.example.com
http://example.com

关于ruby-on-rails - 使用 Rails 3.1 的 Heroku 中特定于 SSL 的主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8482751/

相关文章:

ruby-on-rails - 未定义的方法 `dangerous_class_method?'

ruby-on-rails - Ruby 入门指南:未初始化常量 PostsController::Posts

ruby-on-rails - ActsAsTaggableOn 未定义方法 '[]=' 为 nil :NilClass - Create Action

ruby - 如何从头开始重新启动脚本?

authentication - 客户端 SSL 身份验证导致 IIS 出现 403.7 错误

php - 如何以编程方式安装 ssl 证书 (OpenSSL)

ssl - 如何生成 PEM 文件来安装我自己的 SSL 证书?

ruby-on-rails - 如何在 Rails 4.2 中启用 gzip 文件创建?

ruby-on-rails - 如何根据表列安排任务?

ruby - ||= 在 Ruby 线程中安全吗?