How to use Cloudflare Page Rules to optimize cost for CDN

Today, I'll work around Cloudflare Page Rules to optimize cost for CDN. As you know, Cloudflare is a DNS manager (and many other great features as CDN, Proxy, Firewall, Web3,...). For proxy, It can help your sites completely anonymous since your sites are behind the proxy Cloudflare's servers and it's completely free. So, how to use Cloudflare's Page Rules feature to optimize cost for CDN?
What Cloudflare Page Rules?
As Cloudflare's blog wrote:
Page Rules is a powerful new set of tools that allows you to control how CloudFlare works on your site on a page-by-page basis. The feature provides many of the most popular controls of HTACCESS with a user-friendly interface. Page Rules are now available for all users from the Settings menu next to each domain on the My Websites page.
Use Cloudflare as a CDN
If you using Cloudflare's proxy feature, you can consider you are using a CDN. By default, Cloudflare respects the origin web server’s cache headers in the following order unless an Edge Cache TTL page rule overrides the headers.
- Cloudflare does not cache the resource if the
Cache-Control
header is set toprivate
,no-store
,no-cache
, ormax-age=0
or if there is a cookie in the response. - Cloudflare caches the resource in the following scenarios:
- The
Cache-Control
header is set topublic
and themax-age
is greater than 0. - The
Expires
header is set to a future date.
- The
- If both the
max-age
and anExpires
header are set,max-age
is used.
So basic, Cloudflare will cache resoures on time which your server provide. To optimize this, We'll override cache time. The below picture will show how to create page rules for override cache time:
Optimize cost for CDN
In this post, I'll use AWS S3 as storage server, you can use anything which provide directly url to static assets.
This is setup on Cloudflare:
This is setup on AWS S3 using Static Website Hosting feature: As you see, we are using AWS S3 as storage server and Cloudflare as CDN. By using this, we was optimize cost for CDN's bandwidth
Pros
- Optimize cost for CDN's bandwidth.
- Enable firewall.
Cons
- Download speed slow (3-4MB/s).
- Response time isn't immediately.
Because this is free solution and same as a trick, this is recommend for persional use, small business. If you were used AWS CloudFront, the download speed is very high and response time can be immediately.