簡體   English   中英

使用Nginx在Rails中強制已登錄用戶的SSL

[英]Force ssl for logged in users in rails using 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

問題在於所有請求看起來都像http,因為nginx處理ssl並轉發到thin並導致無限重定向循環。 在這種情況下,為登錄用戶設置ssl的正確方法是什么?

您可以使用proxy_set_header指令設置自定義標頭,以告訴后端請求來自安全前端。

例:

for 80:
proxy_set_header           X-SSL     0;

for 443:
proxy_set_header           X-SSL     1;

或全球

proxy_set_header X-Forwarded-Proto $scheme;

為什么不對所有用戶僅使用https?

Google,Github和其他人可能已經開始這樣做了。

您可以直接在nginx配置中執行此操作。

server {
  listen 80;

  location / {
    rewrite ^(.*) https://$host$1 permanent;
  }

這會將所有端口80流量重定向到https和端口443。

然后,只需為端口443聲明普通服務器即可。

server {
  listen 443;
  // whatever
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM