.htaccesshttpscloudflarecdn

.htaccess redirect to www only works with HTTP (not HTTPS) when using Cloudflare


Friend got her .htaccess changed by the hosting tech support to make her website work with Cloudflare CDN.

.htaccess looks like this:

RewriteEngine On

RewriteCond %{SERVER_PORT} !=443

RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

The purpose is to redirect all traffic to HTTPS + www.

Problem is:

When you go http://example.com the redirect to www works.

But when you go https://example.com the redirect to www doesn't work.

This is because of the RewriteCond as I understand. It makes the rule work only if not on port 443 (which is the HTTPS port).

But this rule seems to be necessary for Cloudflare, because the tech support put it in, and because without it the site doesn't load, looks like it might getting in some redirect loop.

how can we rewrite the file to make it work in all cases, and not break the Cloudflare integration?


Solution

  • Without a condition, it was always redirecting, that is why support had you add a condition. However that condition only handles HTTP to HTTPS. It should also redirect if the host name isn't correct. You can add a second condition to take care of incorrect host names:

    RewriteEngine On
    
    RewriteCond %{SERVER_PORT} !=443 [OR]
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]