Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force_ssl redirect loop on Rails 4 using CloudFlare SSL

I get a redirect loop on my Rails 4 app when enforcing ssl with the force_ssl method (SSL implemented using CloudFlare's one-click SSL capabilities).

like image 670
neurodynamic Avatar asked Oct 05 '15 19:10

neurodynamic


People also ask

How do I fix too many redirects Cloudflare?

Too Many Redirects If you're receiving the ERR_TOO_MANY_REDIRECTS error when accessing your HTTPS enabled site that is being proxied through Cloudflare, it's likely that you have SSL set to Flexible. This should be set to Full (strict), which will ensure connections to your site are fully encrypted end-to-end.

How do I disable enable Always use HTTPS in Cloudflare?

To enable or disable Always Use HTTPS with the API, send a PATCH Open external link request with the value parameter set to your desired setting ( "on" or "off" ).


2 Answers

This stopped happening when I switched from "flexible" to the "full" SSL setting in CloudFlare.

like image 67
neurodynamic Avatar answered Sep 28 '22 05:09

neurodynamic


Cloudflare's trying to force connect via HTTP because your server doesn't have HTTPS, but your app is forcing SSL.

Problem

This happens in a specific set of circumstances:

  1. Your Cloudflare (CF) SSL setting is Flexible and HTTP is allowed between CF and Heroku.
  2. Your server or Heroku instance's SSL isn't setup, so it's forcing the connection between HTTP

What happens is:

  1. You connect to the domain via HTTPS
  2. Cloudflare steps in to handle the SSL part, and tries to fetch the app over plain HTTP from the server
  3. The server sees a connection over HTTP and redirects to HTTPS
  4. Go to step 1

This causes an infinite redirect loop.

Solution

Upgrade your application server to HTTPS, this solves the redirect issue. Then, just to be safe, switch Cloudflare to Full.

First: I configured SSL on my server. In my case, I was using Heroku, which can use Let's Encrypt to provision SSL automatically. You would use Let's Encrypt directly if you weren't. Cloudflare also provides self-signed origin certificates, but why bother when Let's Encrypt is easy and free.

Second: I configured my app to force SSL by adding the following to production.rb

config.force_ssl = true

Third: Since I no longer needed an HTTP connection between my server and Cloudflare, I switched it to from Flexible to Full. If you've used Let's Encrypt or a CA to provision the server's certificate, you can switch to Flexible (Strict).

like image 43
Amin Shah Gilani Avatar answered Sep 28 '22 06:09

Amin Shah Gilani