HTTPS, CakePHP, and Cloudflare

By zhunt / 19th June, 2020

I’ve been using Dreamhost for a few years, as well as making it easy to run the newest versions of PHP, it also has easy to set-up Lets Encrypt and Cloudflare support. Getting a CakePHP site with Lets Encrypt was easy, but adding Cloudfare to the mix gave an odd error. Turns out the solution was a small adjustment.

One issue I’ve had is getting the https redirects running as well as Cloudflare together.

Usually on a site, I start with setting it up, then once it’s running fine, I’ll turn on Cloudflare to get a bit of extra speed. After that I selected Lets Encrypt. This is when the problem started.

The problem how I was setting-up the re-write rules, I was sticking something like:

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

At the top of my .htaccess file before default code that CakePHP comes with:

# Uncomment the following to prevent the httpoxy vulnerability
# See: https://httpoxy.org/
#<IfModule mod_headers.c>
#    RequestHeader unset Proxy
#</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^(\.well-known/.*)$ $1 [L]
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>

CakePHP, of course, has 2 .htaccess files, one at the root level and another in the /webroot folder, the file I’m editing is the one at the root level like so:

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

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^(\.well-known/.*)$ $1 [L]
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>

Now the problem is this sometimes seemed to work for a bit, then stop working in anywhere from a few minutes to an hour – usually corresponding to anytime I didn’t have easy access to the server.

The error was something like “too many redirects. Try clearing your browser’s cookies” Needless to say, clearing cookies did nothing.

Finally decided to look into it, thanks to gabrielkolbe on StackOverflow, turns out the correct way to do it is like so:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP:X-Forwarded-Proto} =http
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]
    RewriteRule    ^(\.well-known/.*)$ $1 [L]
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>

Simply moving the https rewrite rules from above and into the block with the rest of Cake’s rules fixed the problem.

That’s it, after this, turn back on Cloudflare and it should start working in a few minutes.

About the author

zhunt