Question

I use Cloudflare free CDN and because I need to use https in some areas, I'm no able to activate it on the main domain. So after a little google research, i founded that i can replace selected files formats to a url (as a mirror/cdn) but couldn't make it work.

So basically this is what I want to do, when people/website/script request or visit maindomain.com/img.png redirect it to cdn.cdn.com/img.png (where "cdn.cdn.com" is setup in the same folder as an addon domain and loads same htaccess) and automatically serve img.png without make any code change. This because cloudflare allow to cache content through a CNAME record, so i want to automatically replace maindomain.com to the CDN CNAME record (cdn.cdn.com). Also, I would like to know how to make it work for a single folder.

This is one code that I tested

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^maindomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.maindomain\.com$
#if you want to apply to a single folder 
RewriteCond ^htatest\
RewriteCond $1 "\.(jpg|png)$" [NC]
RewriteRule ^(.*) http://cdn.cdn.com/$1 [L]
</IfModule>
Was it helpful?

Solution

Replace your rule with this:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?maindomain\.com$ [NC]
RewriteRule ^(htatest/.+?\.(?:jpg|png))$ http://cdn.cdn.com/$1 [L,R=301,NC]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top