Last Updated on May 21, 2019 by Amit

If you are hosting your domain on cloudflare CDN then one of the starngest issues you might face is Apache ssl redirection. Your normal apache htaccess http to https RewriteRule might fail to work. The reason why it fails is because your domain is on a proxy server and not on the server you are hosting your files. Your server receives proxied requests from Cloudflare. And this way one of the mod-rewrite variables that gets effected is %{HTTPS} . Normally this variable is used to check the requested URL scheme (http or https) in a RewriteRule . When your server gets a proxied request from cloudflare this variable gets ignored as Cloudflare doesn’t recognise this .
Cloudflare sets a URL scheme environment variable (%{HTTP:CF-Visitor}) when a url is requested. You can check that variable using a RewriteCond to know which URL scheme your current URL is using.

HTTP to HTTPS RewriteRule for cloudflare

htaccess or server.config rule for Cloudflare users:

RewriteEngine On
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

Redirect https to http cloudflare htaccess

If you want redirect https URLs to http , then you might replace http with https in the condition pattern and replace https with http in the destination URL , the following rule example does it :

RewriteEngine On
RewriteCond %{HTTP:CF-Visitor} '"scheme":"https"'
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

Redirect a single URL to https Cloudflare htaccess

If you need to redirect a specific URL to https , then you can add that URL path to the pattern of RewriteRule .For example (.*) regex pattern in the rule dynamically matches all URL paths, you can replace it with ^thispath$ so it applies only to that path.

RewriteEngine On
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^thispath$ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

Enforce SSL using cloudflare settings

You can also enforce SSL on your domain using Cloudflare if you don’t want to use RewriteRules. To enforce it through Cloudflare, go to dashboard >page rules on Cloudflare and create a rule that redirects your site URLs to https . The following CF screenshot might help you :

Press “Save and deploy” to save your settings on Cloudflare. You also need to clear your browser cache after making these changes.

Hope you liked it! Please post a comment bellow if you need my help with RewriteRules or just to say thanks.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.