in Apache, NGINX, Security

Forcing HTTPS Redirection and Cloudflare’s Flexible SSL


CloudFlare launched Universal SSL, making SSL encryption available to everyone. 2 million sites have already signed up for the service.

It’s very easy to setup a Flexible SSL. It only takes only 48hours to be active.

But if you force http to https redirection on your website with the following normal methods, a loop redirection occurs.

To redirect a user from HTTP to HTTPS, you can use the following:

RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' 
RewriteRule ^(.*)$ https://www.domain.com/$1 [L]

Similarly, to require all traffic go over HTTPS on CloudFlare, you can use the following:

RewriteCond %{HTTP:CF-Visitor} !'"scheme":"http"' 
RewriteRule ^(.*)$ https://www.domain.com/$1 [L]
FLEXIBLE SSL HTTPS REDIRECTION FOR NGINX
location / { 
  if ($http_x_forwarded_proto != "https") { 
    rewrite ^(.*)$ https://$server_name$1 permanent; 
  }
FLEXIBLE SSL HTTPS REDIRECTION VIA PHP
if ( isset( $_SERVER['HTTP_CF_VISITOR'] ) && strpos( $_SERVER['HTTP_CF_VISITOR'], 'https' ) !== false ) { 
  $_SERVER['HTTPS'] = 'on'; 
}

OR

if($_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") { 
  header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); 
  exit(); 
}

You can also use the Cloudflare Pagerules to force the https protocol.

For WordPress, there is a working plugin available called “Cloudflare Flexible SSL”, I also use “SSL Insecure Content Fixer” to load “unsafe scripts” in the admin section.