Skip to content

Instantly share code, notes, and snippets.

@thagxt
Last active September 6, 2021 15:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thagxt/16638cf075a06a051601 to your computer and use it in GitHub Desktop.
Save thagxt/16638cf075a06a051601 to your computer and use it in GitHub Desktop.

Forcing HTTPS Redirection and Cloudflare’s Flexible SSL

If you force http to https redirection on your website, while using CloudFlare, with the following normal methods, a loop redirection occurs.

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

Normal Redirect via PHP

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

Understanding the problem

SSL between the visitor and CloudFlare — visitor sees HTTPS on your site, but no SSL between CloudFlare and your web server. You don’t need to have an SSL cert on your web server, but your visitors will still see the site as being HTTPS enabled.

There is an encrypted connection between your site visitors and CloudFlare, but not from CloudFlare to your server.

The HTTPS condition from the htaccess or PHP will always return as off, as server is still using the http protocol.

Hopefully, there are some alternative methods to force the https redirects Flexible SSL https redirection via .htaccess (for apache)

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

Here’s the solution (for apache only) from the Cloudflare’s blog.

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();
}

@ https://support.cloudflare.com/hc/en-us/articles/200170536-How-do-I-redirect-HTTPS-traffic-with-Flexible-SSL-and-Apache- @ https://gomah.fr/server-tips/forcing-https-redirection-and-cloudflares-flexible-ssl/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment