3

I usually set up my sites to rewrite URLs in the following cases:

  1. All http traffic is redirected to https (and www), with a 301
  2. All non-www traffic is redirected to www (and https), with a 301

In .htaccess, the rewrite rules are as follows:

RewriteEngine on
RewriteCond %{http_host} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

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

Note that all redirects are achieved with only one hop. Non-www traffic goes to www and https, and non-https traffic goes to https and www. How do you achieve the same results in Cloudflare?

P.S. I'm not sure if Cloudflare's "Always Use HTTPS" option is worth enabling since it doesn't use a 301 and I have to write a separate rule for a https redirect rule with a 301 anyway.

1

https://www.bybe.net/cloudflare-enforce-ssl-redirect-http-https/ has the full details.

To redirect to HTTPS, you need add a "Page Rule" for http://*example.com/* with the "Always Use HTTPS" option from the settings.

To redirect to www you need three "Page Rules":

  • http://example.com/* -> https://www.example.com/$1
  • https://example.com/* -> https://www.example.com/$1
  • http://www.example.com/* -> https://www.example.com/$1

Alternately, you could just leave your .htaccess rules in place. You rule for the http_host should continue to work unmodified, even post-CloudFlare because CloudFlare should forward the Host: example.com header. You would just need to chang the condition on your HTTPS rule to use the X-Forwarded-Proto header that CloudFlare sets to let you know if the request was http or https.

RewriteCond %{HTTP:X-Forwarded-Proto} http
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
  • So you're saying it can't be done with the free tier, since that only includes 3 rules. – Knocks X Nov 12 at 21:54
  • If that is the case, no need to pay for a tier because of this. I added an alternative to my answer. – Stephen Ostermiller Nov 12 at 23:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.