使用nginx强制ssl为rails中的登录用户

jhc*_*hen 2 ssl ruby-on-rails nginx

我的堆栈看起来像这个nginx - > thin - > rails.在我的rails应用程序中,我有我的applicaton_controller.rb:

  if (!Rails.env.development?)
    before_filter :force_ssl
  end

  # Force logged in users to use SSL
  def force_ssl
    if current_user && request.protocol != "https://"
      redirect_to :protocol => "https://"
    end
  end
Run Code Online (Sandbox Code Playgroud)

问题是所有请求看起来像http,因为nginx处理ssl并转发为thin并导致无限重定向循环.在这种情况下,为登录用户设置ssl的正确方法是什么?

Mar*_*urt 5

您可以使用proxy_set_header指令设置一个自定义标头,告诉后端该请求来自安全前端.

例:

for 80:
proxy_set_header           X-SSL     0;

for 443:
proxy_set_header           X-SSL     1;
Run Code Online (Sandbox Code Playgroud)

或全球

proxy_set_header X-Forwarded-Proto $scheme;
Run Code Online (Sandbox Code Playgroud)