How to Rewrite to Point to a CDN

.htaccesscdn

I'm hoping to use a CDN to deliver all our image files. We call the images by simply using the CDN's domain instead of our own. I could easily change the domain reference in our content management system, but then preview breaks because it's looking for an image that doesn't yet appear on our external server for our CDN to pull from. As soon as we publish, the CDN has an image to pull.

I'm thinking that I could add a rule in our external site .htaccess file to redirect any requests for images from our /webfiles folder to the appropriate folder on our CDN. I realized that when the CDN tries to harvest the image it would be sent back to its own server so I've added a referrer line so that only request from our server will pull the CDN version. I'm reluctant to try this on our live server until I get some knowledgeable feedback. Does this approach make sense? Would this be the right order? (I would test using a 302 first.)

RewriteCond %{HTTP_REFERER} ^https://www.example.com [NC]
RewriteCond %{REQUEST_URI} ^\.(jpg|jpeg|png|gif|webp)$ [NC]
RewriteCond %{HTTP_HOST} ^(.*)www.example.com/webfiles/$ [NC]
RewriteRule ^(.*)$ http://example-cdn.com/webfiles/$1 [R=301,L]

Best Answer

Adding a redirect like this defeats the purpose of CDN in many ways. When clients request an image file, they first send request to your server, which responds with redirect, and then clients request it from CDN.

This adds considerable latency to image loading.

You should change CMS so that in preview it uses URLs from your server, but for front-end it uses URLs to CDN.

Related Topic