简体   繁体   中英

Force ssl for logged in users in rails using nginx

My stack looks like this nginx -> thin -> rails. In my rails app I have in my 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

The problem is all requests seem like http since nginx handles the ssl and forwards to thin and causes an infinite redirect loop. What's the proper way to set up ssl for logged in users in this situation?

You can use the proxy_set_header directive to set a custom header telling your backend that the request came from the secure frontend.

Example:

for 80:
proxy_set_header           X-SSL     0;

for 443:
proxy_set_header           X-SSL     1;

Or globally

proxy_set_header X-Forwarded-Proto $scheme;

Why not just use https for all users?

Google, Github, and may others have starting doing it.

You can do this straight in your nginx config.

server {
  listen 80;

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

This will redirect all port 80 traffic to https and port 443.

Then just declare your normal server for port 443.

server {
  listen 443;
  // whatever
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM