Cloudflare‘s caching messes up .htaccess

I‘m using the rewrite mod in .htaccess to load .webp images for browsers which supports it and for the ones which doesn‘t is uses .jpg, however when cloudflare is enabled it is messed up. What I know so far is that when I turn on developer mode everything works fine (as the caching is disabled). When I purge everything then when the first browser connects, let‘s say chrome then it caches the .webp file and for every other browser it will only show that one, which is quite a bit of problem as safari can‘t display it. On the other hand if safari connects first, it caches the .jpg file which in this case kills the whole purpose of this. I also use this to load different sized pictures for mobile devices.

Here is the code I use:

<IfModule mod_setenvif.c>
  SetEnvIf Request_URI "\.(jpe?g|png)$" REQUEST_image
</IfModule>
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_ACCEPT} image/webp
  RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp]
</IfModule>
<IfModule mod_mime.c>
  AddType image/webp .webp
</IfModule>
<IfModule mod_headers.c>
  Header append Vary Accept env=REQUEST_image
</IfModule>
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} "(android|blackberry|googlebot-mobile|ipad|iemobile|iphone|ipod|palmos|webos)" [NC]
    RewriteRule "^desktop/(.*)$"  "/mobile/$1" [L] 
</IfModule>

The issue here is that Cloudflare (but the same would be valid for any CDN) will cache the first file return for a specific URL, if that is the WebP image it will send that, if it’s the JPG it will cache that.

You can’t change the contents of an URL if the caching is enabled. Three solutions:

  1. do not cache those URLs (or at least the WebP ones) and send all requests to the origin.
  2. use a Worker to do the job the .htaccess file does and request images from the server depending on it, you won’t have to serve the assets from the origin because they can be cached being 2 different URL from the origin and one to the clients.
  3. upgrade to the Pro plan and let Cloudflare do the same job as you are doing there without the cache issues.
2 Likes

This topic was automatically closed after 30 days. New replies are no longer allowed.