Heroku中使用Rails 3.1的特定于SSL的主机名

Eri*_*ang 5 ruby ssl https ruby-on-rails hostname

我目前有一个设置,在我的应用程序控制器中使用此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
Run Code Online (Sandbox Code Playgroud)

我想做的是https://secure.example.com在使用SSL时使用,但http://example.com在不使用SSL时继续使用.有没有办法可以在主机名之间切换,具体取决于我是否使用SSL?

dig*_*ter 4

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

\n\n

Rails >= 3.1 \n只需在您的环境配置中

使用即可。config.force_ssl = true

\n\n
# config/application.rb\nmodule MyApp\n  class Application < Rails::Application\n    config.force_ssl = true\n  end\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
# config/application.rb\nmodule MyApp\n  class Application < Rails::Application\n    config.force_ssl = false\n  end\nend\n\n# config/environments/production.rb\nMyApp::Application.configure do\n  config.force_ssl = true\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n

导轨 < 3.1

\n\n

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

\n\n

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

\n\n

请注意,I\xe2\x80\x99mRack::SSL作为字符串传递,以委托在 Rails 应用程序初始化结束时加载类。另请注意,中间件必须插入堆栈中的特定位置,至少在ActionDispatch::Static和之前ActionDispatch::Cookies

\n\n

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

\n\n
# Gemfile\ngem \'rack-ssl\', :require => \'rack/ssl\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

并行启用 HTTPS 和 HTTP

\n\n

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

\n\n

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

\n\n
config.middleware.insert_before ActionDispatch::Static, Rack::SSL, :exclude => proc { |env| env[\'HTTPS\'] != \'on\' }\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

https://secure.example.com
\nhttp://example.com

\n