Firefox 和 Chrome 继续使用 nginx/Passenger 在 Rails 应用程序上强制使用 HTTPS

Ste*_*eve 7 ssl nginx https ruby-on-rails phusion-passenger

我在这里遇到了一个非常奇怪的问题,每次我尝试在非 SSL 模式下浏览我的 Rails 应用程序时,Chrome (v16) 和 Firefox (v7) 一直强制我的网站在 HTTPS 中提供服务。

我的 Rails 应用程序使用 Capistrano、nginx、Passenger 和通配符 SSL 证书部署在 Ubuntu VPS 上。

我在 nginx.conf 中为端口 80 设置了这些参数:

            passenger_set_cgi_param HTTP_X_FORWARDED_PROTO http;
            passenger_set_cgi_param HTTPS off;
Run Code Online (Sandbox Code Playgroud)

我的 nginx.conf 的长版本可以在这里找到:https : //gist.github.com/2eab42666c609b015bff

ssl-redirect.include 文件包含:

rewrite ^/sign_up https://$host$request_uri? permanent ;
rewrite ^/login https://$host$request_uri? permanent ;
rewrite ^/settings/password https://$host$request_uri? permanent ;
Run Code Online (Sandbox Code Playgroud)

这是为了确保这三个页面在来自非 SSL 请求时使用 HTTPS。

我的 production.rb 文件包含这一行:

  # Enable HTTP and HTTPS in parallel
  config.middleware.insert_before Rack::Lock, Rack::SSL, :exclude => proc { |env| env['HTTPS'] != 'on' }
Run Code Online (Sandbox Code Playgroud)

我尝试通过 nginx 重写重定向到 HTTP,Ruby on Rails 重定向,还使用 ​​HTTP 协议使用 Rails 视图 url。

我的 application.rb 文件包含在 before_filter 钩子中使用的以下方法:

def force_http
 if Rails.env.production?
   if request.ssl?
     redirect_to :protocol => 'http', :status => :moved_permanently
   end
 end
end
Run Code Online (Sandbox Code Playgroud)

每次我尝试重定向到 HTTP 非 SSL 时,浏览器都会尝试将其重定向回 HTTPS,从而导致无限重定向循环。然而,Safari 工作得很好。即使我在 nginx 中禁用了 SSL 服务,浏览器仍会尝试使用 HTTPS 连接到该站点。我还应该提到,当我将我的应用程序推送到 Heroku 时,Rails 重定向适用于所有浏览器。

我想使用非 SSL 的原因是我的主页包含非安全动态嵌入对象和非安全 CDN,我想防止安全警告。

我不知道是什么导致浏览器不断强制 HTTPS 请求。

小智 9

如果您config.force_ssl = true在您的环境配置中使用,然后将其关闭,您的浏览器可能仍然只能通过 ssl 进行连接。

当为 true 时,Rails 会发送一个HSTS 标头force_ssl,这将导致一些浏览器只允许通过 HTTPS 连接到相关域,而不管地址栏中输入了什么。默认情况下,此设置将被浏览器缓存 1 年。

在此博客文章中查看有关如何避免这种情况的一些提示:http : //www.simonecarletti.com/blog/2011/05/configuring-rails-3-https-ssl/#comment-40447


小智 5

我在所有地方的 Wordpress 支持论坛上找到了一种关闭 HSTS 的方法:https : //wordpress.org/support/topic/want-to-turn-off-http-strict-transport-security-hsts -header#post-6068192

您可以发回一个将关闭 HSTS 缓存的标头。在 Chrome 中使用此示例 before_filter 在 Rails 4 应用程序中进行测试:

response.headers['Strict-Transport-Security'] = 'max-age=0; includeSubDomains'
Run Code Online (Sandbox Code Playgroud)