title: Why am I getting infinite redirect loop with force_ssl in my Rails app?
body: <p>I want to have my API controller use SSL, so I added another listen directive to my nginx.conf</p>
  
  <pre><code>upstream unicorn {
    server unix:/tmp/unicorn.foo.sock fail_timeout=0;
  }
  
  server {
    listen 80 default deferred;
    listen 443 ssl default;
    ssl_certificate /etc/ssl/certs/foo.crt;
    ssl_certificate_key /etc/ssl/private/foo.key;
  
    server_name foo;
    root /var/apps/foo/current/public;
  
    try_files $uri/system/maintenance.html $uri/index.html $uri @unicorn;
  
    location @unicorn {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_pass http://unicorn;
    }
  
    error_page 502 503 /maintenance.html;
    error_page 500 504 /500.html;
    keepalive_timeout 5;
  }
  </code></pre>
  
  <p>which passes the nginx conftest without any problems. I also added a <code>force_ssl</code> directive to my ApiController</p>
  
  <pre><code>class ApiController &lt; ApplicationController
    force_ssl if Rails.env.production?
  
    def auth
      user = User.authenticate(params[:username], params[:password])
      respond_to do |format|
        format.json do
          if user
            user.generate_api_key! unless user.api_key.present?
            render json: { key: user.api_key }
          else
            render json: { error: 401 }, status: 401
          end
        end
      end
    end
  
    def check
      user = User.find_by_api_key(params[:api_key])
      respond_to do |format|
        format.json do
          if user
            render json: { status: 'ok' }
          else
            render json: { status: 'failure' }, status: 401
          end
        end
      end
    end
  end
  </code></pre>
  
  <p>which worked just fine when I wasn't using SSL, but now when I try to <code>curl --LI http://foo/api/auth.json</code>, I get properly redirected to <code>https</code>, but then I keep on getting redirected to <code>http://foo/api/auth</code> ending in an infinite redirect loop.</p>
  
  <p>My routes simply have</p>
  
  <pre><code>get "api/auth"
  get "api/check"
  </code></pre>
  
  <p>I'm using Rails 3.2.1 on Ruby 1.9.2 with nginx 0.7.65</p>