Preface
In the completed CF series tutorials ”1” to ”5”, besides the foundation trilogy of ”1” to ”3”, in the subsequent ”4” and ”5” I introduced CF WAF and CF DDoS protection respectively, because I believe these 2 features are the most valuable key features in the CF traffic sequence, deserving detailed introductions in their own dedicated sections.
However, because everyone's actual environment and needs are different, there are many other features in the CF traffic sequence, which can be considered valuable key features for those who need them, such as Cache Rules.
Actually, the CDN feature provided by Cache Rules should have been the most popular feature of CF. However, due to the unique nature of the domestic network environment, after Free plan users use CF's CDN, both the access addresses assigned to visitors and the locations where origin requests are initiated are highly likely to be assigned to CF data centers in the US (mostly the San Jose data center in the US West). This makes the visitor experience highly likely to be slower than accessing directly without using CF CDN (after all, the round trip has to cross the Pacific), which is why it is known as a ”negative optimization” for domestic access.
However, except for domestic visitors and a few similar special countries, the access experience in other regions of the world is still quite good, so CF's CDN feature is still necessary to configure (especially for those whose strategy focuses globally rather than just domestically).
In addition, for certain content (such as images on image hosting sites), being a little slower is actually not very noticeable, so CF's Cache Rules are indeed one of the most important and valuable features.
Cache Rules
Introduction to Cache Rules
By default (when no cache rules are configured), CF only applies to static resources with certain extensions (TTL is generally 2 hours). These static resources include but are not limited to:
- Image files:
.jpg, .jpeg, .png, .gif, .ico, .svg, etc. - Font files:
.woff, .woff2, .ttf, .otf, .eot, etc. - CSS files:
.css - JavaScript files:
.js - Multimedia files:
.mp3, .mp4, .avi, .mkv, .webm, .ogg, etc. - Document files:
.pdf, .doc, etc.
This is very inconvenient, as I might have other normal requirements, such as:
- I don't want to cache video files with the .mkv extension because there are many such large video files on my website, and if they are cached and traffic is high, it could easily lead to my account being banned by CF.
- I want to cache HTML files, but the default static resources do not include HTML.
- The default 2 hours is too short; I want to cache for a longer time.
- ........
Custom requirements like the ones above are too numerous and common. To address users' normal and common custom caching needs, CF introduced Cache Rules.
CF's Cache Rules feature allows users to customize caching behavior based on specific conditions and needs, thereby controlling what content is cached by the CDN and browser and for how long, ultimately optimizing website content loading speed and caching efficiency.
The main features and characteristics of Cache Rules are as follows:
- Flexible Cache Control: Users can set rules to define which content should be cached and which should not. For example, specific paths, request headers, query parameters, etc., can be specified to control caching behavior.
- Support for complex conditions: Cache Rules support matching based on multiple conditions such as URL path, HTTP headers, and query parameters. Users can create complex caching strategies, such as caching specific file types or geo-based caching strategies.
- Priority management: Users can set priorities for different cache rules to ensure that high-priority rules are executed first in cache control, helping to achieve more precise cache management.
- Differentiation between dynamic and static content: Users can set different caching strategies based on the content type (static or dynamic) to optimize cache hit rates and server load.
- Real-time activation and debugging: Rule changes take effect in real time. Users can manage and debug them through Cloudflare's dashboard or API, making it easy to quickly adjust and test caching strategies.
- Integration with other Cloudflare services: Cache Rules integrate with other Cloudflare services (such as WAF, Rate Limiting, Argo Smart Routing, etc.) to provide more comprehensive security and performance optimization features.
Cache Rules Getting Started Guide
Composition of Cache Rules
A Cache Rule consists of two parts: incoming request matching and cache eligibility.
Incoming Request Matching
It allows users to set specific conditions for incoming request matching, serving as a prerequisite determination for whether to cache subsequently.
Common matching conditions include the following:
- URL path
• Matching based on URL path, such as specific folders or file extensions.
• Supports wildcard and regular expression matching. - Hostname
• Matching based on the requested hostname. - Query parameters
• Matching based on the query parameters of the request, allowing cache control for requests with specific parameters. - HTTP request method
• Matching based on HTTP request methods such as GET, POST, etc. - HTTP request headers
• Matching based on specific request headers, such as User-Agent, Accept-Language, etc. - Cookie
• Matching based on specific cookies contained in the request.
Other optional conditions include: Referer, SSL/HTTPS, User Agent, X-Forwarded-For, etc.
Cache Eligibility
For traffic flows that match the configured incoming request criteria, there are two choices: bypass cache or eligible for cache.
- Bypass cache
• Instructs CF not to cache the origin server's response to requests that match the incoming criteria, typically used for requests accessing dynamic content or content requiring login.
• The only optional setting is Browser TTL.

- Eligible for cache
• Instructs CF to cache the origin server's response to requests that match the incoming criteria, typically used for requests accessing static content.
• There are 6 optional settings, among which Edge TTL and Browser TTL are the most commonly used. This article will use these two options as examples for demonstration:

Note: Edge TTL refers to the duration static content remains in CF's edge cache, while Browser TTL refers to the duration static content remains in the browser's local cache. Generally, to ensure consistency in page content display, the Browser TTL should be shorter than the Edge TTL.
Cache Rules Configuration Logic
In the Free plan, Cache Rules have a quota of 10 rules, which is sufficient for most users. However, there are a few points to note regarding the configuration logic.
The smaller the rule number, the higher the priority. Therefore, you need to organize the logical order of your cache rules and place high-priority rules first—typically, rules that bypass cache should come first, as shown in the figure below:

Non-dynamic content of dynamic websites can also be cached, but the dynamic content parts must first be excluded in the higher-priority "bypass cache" rules.
In the traffic sequence, Cache Rules have a higher priority. Therefore, if a request needs to be processed by a lower-priority node feature in the traffic sequence (such as Workers), you must ensure that the request hits the ”Bypass cache” of the cache rules rather than ”Eligible for cache”.
If you host multiple subdomain websites under a second-level domain, and they contain both dynamic and static content, it is best to include the hostname as a limiting condition when creating cache rules to avoid confusing caching logic.
Cache Rules Configuration Examples
Static Websites
Taking my multi-site navigation page URLwww.tangwudi.comas an example, assuming the image hosting URL used isimage.tangwudi.com, and the API path used iswww.tangwudi.com/api*, according to the configuration logic of the cache rules mentioned earlier, it should be set as follows:
APIs are dynamic content and need to bypass cache.

Cache images from the image host.


Note: Edge TTL and Browser TTL are optional; if not set, the default is 2 hours. For static content like images, whether to set a TTL or how long to set it depends on the type of website, primarily based on the frequency of image updates. For my multi-site navigation homepage, the images rarely change, so they can be set for as long as possible—for example, setting Edge TTL directly to 1 year is perfectly fine. As for Browser TTL, theoretically, 1 year is also fine, but unnecessary; 1 month is safe enough, and the same logic applies to static personal blog websites.
Caching of other static content (mainly HTML)

Edge TTL and Browser TTL are the same as image cache:

Final completed effect:

Note 1: The TTL (Edge TTL and Browser TTL) for image cache and HTML cache in this example is the same. Theoretically, the two rules could be combined into one. However, this is only due to the specificity of this example. Generally speaking, it is unlikely that the TTL for image cache and HTML cache would be the same, so using two separate ”eligible for cache” rules is reasonable. Cached content with different TTLs needs to be set using different rules. As for how many cache rules are ultimately needed, it is determined by the granularity of the website content's cache control.
Note 2: Please replace the hostname ”blog.tangwudi.com“ with your actual hostname based on your actual environment.
Dynamic Websites
My blog is built using WordPress, which is representative of dynamic blog types, so I will use my blog URLblog.tangwudi.comas an example. In this example, it is assumed that images are uploaded to WordPress's own media library and no external image hosting is used. Since the dynamic content of WordPress sites has its own characteristics, such as specific URIs (content starting with “/wp-admin”, ”/wp-login”, ”/wp-comment”, etc.) and requests containing specific cookie fields (wp-, logged_in, wordpress, comment_, woocommerce_) cannot be cached, to ensure accuracy, a layered rule matching approach is adopted. The recommended configuration rules are as follows:
Bypass caching for access requests whose access links contain special URIs with dynamic content (matching at the URI level)
Note the operators of the rules. The operators for the URI paths here are all ”contains” (this is to be lazy; of course, you can also choose the operator ”starts with”, in which case you must write it in the correct format, for example, ”starts with” followed by ”/wp-admin”):

The expression is:
(http.host eq "blog.tangwudi.com" and http.request.uri.path contains "wp-admin") or (http.host eq "blog.tangwudi.com" and http.request.uri.path contains "wp-login") or (http.host eq "blog.tangwudi.com" and http.request.uri.path contains "wp-comment") or (http.host eq "blog.tangwudi.com" and http.request.uri.path contains "?s=") or (http.host eq "blog.tangwudi.com" and http.request.uri.path contains "xmlrpc") or (http.host eq "blog.tangwudi.com" and http.request.uri.path contains "preview=true")
Bypass caching for access requests where the cookie contains specific characters when accessing WordPress
Note that the operator for ”Cookie” in each rule is "contains":

The expression is:
(http.host eq "blog.tangwudi.com" and http.cookie contains "_logged_in_") or (http.host eq "blog.tangwudi.com" and http.cookie contains "wordpress") or (http.host eq "blog.tangwudi.com" and http.cookie contains "comment_") or (http.host eq "blog.tangwudi.com" and http.cookie contains "woocommerce_")
Bypass pages ending with .php

Note: Actually, the above two rules are already sufficient to cover dynamic content; this one can only be considered a patch.
Cache image content

Note: For the settings of Edge TTL and Browser TTL in this part, please refer to the description in the earlier part of the article.
Cache HTML

Expression:
(http.host eq "blog.tangwudi.com" and ends_with(http.request.uri.path, ".html") and not http.cookie contains "_logged_in_" and not http.cookie contains "wordpress" and not http.cookie contains "comment_" and not http.cookie contains "woocommerce_") or (http.host eq "blog.tangwudi.com" and ends_with(http.request.uri.path, ".htm") and not http.cookie contains "_logged_in_" and not http.cookie contains "wordpress" and not http.cookie contains "comment_" and not http.cookie contains "woocommerce_")
Note: For the settings of Edge TTL and Browser TTL in this part, please refer to the description in the earlier part of the article.
Cache other content

This is mainly for content other than HTML, such as CSS files, etc.
Note: For the settings of Edge TTL and Browser TTL in this part, please refer to the description in the earlier part of the article.
The final configuration is as follows:

Note 1: Actually, to be less precise, rules 4, 5, and 6 could be simplified by keeping only rule 6, and both 4 and 5 could be deleted directly; the effect would be the same. However, the reason for separating them is to reduce risk and to allow Edge TTL and Browser TTL to be set to their respective suitable values based on different types of cache.
Note 2: Actually, the URI part and the cookie part of the bypass cache rules overlap with each other. Since I do not know enough about the details of WordPress, I wrote them as two rules just to be safe, focusing on safety. In fact, there are definitely many duplicate rules, such as bypassing the cookie part_logged_in_和WordPressThese two are a bit repetitive, but I saw in some materials that they sometimes saywordpress_logged_in, and sometimes saywp_loggen_in, and I didn't bother to look into it deeply, so I just wrote both of them. At most they are redundant, but it's safe.
Note 3: There are various types of websites built with WordPress. Dynamic content on different types of sites may have its own unique URIs or unique cookie values, so you may need to modify the URI part and cookie part according to the characteristics of your own site.
Note 4: Although the above configuration uses WordPress as an example, the configuration logic for other dynamic blogs is the same; just modify it according to the actual situation.
Note 5: Please replace the hostname ”blog.tangwudi.com“ with your actual hostname based on your actual environment.
Note 6: Supplementary update. Although there are no major issues with these WordPress cache rule configurations in actual use, I do not recommend this approach. These rule configurations are just a relatively general and simple demonstration. In fact, different themes may have their own specific cache configuration requirements. Therefore, if you are not familiar with these configurations and do not have sufficient technical support, this approach is not suitable for beginners. In addition, I recently tried the Hexo static blog, switched to the Argon theme, modified the full-screen background image on the homepage, and then published and modified some articles. The whole process almost made me “break down”, especially when constantly clearing the cache, I felt like I was questioning my life. Even static blogs face such trouble, let alone dynamic blogs like WordPress, where cache management is even more complex. If you are very familiar with the WordPress system, cache rules, etc., and can use technical means to optimize cache configurations, it is theoretically possible to achieve results close to APO, such as using Cache-Tag in conjunction with API calls to achieve more efficient cache management. However, this method requires more technical accumulation and daily maintenance investment. If you do not have enough technical accumulation, the simplest and most worry-free solution is to use paid APO, or for users with a limited budget, you can try the free APO "beggar's version" solution (see Part 7 of the Cloudflare Series Tutorials), these solutions allow you to manage cache more easily without worrying too much about details.
Also: In addition to Cache Rules, another feature that can set CF caching behavior is ”Page Rules”, and the processing priority of Page Rules in the traffic sequence is higher than that of Cache Rules:

However, it is generally not recommended to use ”Page Rules” for caching, for the following reasons:
Page Rules only have a quota of 3 (Free plan), which is too few. Moreover, besides caching, Page Rules can also implement many other functions, as follows:



Therefore, Page Rules should be used to implement more complex composite requirements, or for temporary processing of certain special traffic that requires higher priority processing. It would be too wasteful to use them just to implement functions that Cache Rules can already complete (after all, Cache Rules have a quota of 10, which is much more generous than the 3 of Page Rules~).
The matching conditions for Page Rules can only use URLs, which is too simplistic:

Unlike Cache Rules” ”Incoming Request Matching", which supports multiple conditions and combinations of or and and.
The maximum Edge TTL is only one month, while Cache Rules can be set to 1 year:

Actually, another reason is that CF's future attitude is unclear. Around June, Page Rules were actually announced to be deprecated, but for some reason, the deprecation notice was later withdrawn. It's hard to say what will happen in the future, so try not to use them if possible. Even if you have to use them, try to limit them to temporary processing, and usually try to use the existing node functions in the traffic sequence to complete tasks, which is the safest.
“Other Options in the ”Caching" Section
In the ”Caching” section, there are several options that you can configure according to your needs.
Purge Cache

Purging cached files is used to force CF to fetch the latest version of these files from your web server.
You can choose ”Custom Purge” to purge specific URLs (the Free plan can only purge resources that fully match the URL, and does not support*wildcards):

You can also choose ”Purge Everything”:

Caching Level

Caching Level determines how much of your website's static content CF should cache. CF's CDN caches static content according to the following levels:
- No query string
Deliver resources from cache when there is no query string. Example URL:tangwudi.com/pic.jpg - Ignore query string
Deliver the same resource to everyone, regardless of the query string. Example URL:tangwudi.com/pic.jpg?ignore=this-query-string - Standard (default)
Deliver a different resource each time the query string changes. Example URL:tangwudi.com/pic.jpg?with=query
Unless there are special requirements, just keep the default ”Standard”.
Browser TTL

This is actually the default Browser TTL value. If the access request does not match the Browser TTL value set in the cache-related rules, or if the Browser TTL value set by the origin server is less than this value, the value here will be used. You can set this according to your own needs.
Crawler Hints

After studying it carefully, I found this feature quite interesting: when the content of a website hosted on CF changes, this feature records these changes and then provides hints to search engines and other legitimate crawlers about the frequency and importance of content changes. This helps crawlers schedule their crawling plans more intelligently, prioritizing frequently changing or important content to ensure that the information indexed by search engines is up to date. Because crawling efficiency is improved, unnecessary crawls to the origin site are reduced, indirectly lowering the load on the origin server.
P.S. Why do I feel that if Bokeyuan had used CF and enabled this feature back then, the Baidu spider crawler wouldn't have crawled Bokeyuan to the point of crashing?
This feature is disabled by default, there is no danger, and it can be kept enabled.
Always Online™

Simply put, when the origin server fails, if the content of the page the user is visiting is in the cache, CF will directly return this content to the user and display a message at the top of the page: "There is a problem with the origin server, this is just cached content."
The key issue is that this feature is mainly effective for cacheable static content; dynamic content and interactive features (such as user login, shopping carts, etc.) will not work properly when the origin server is unavailable. Therefore, this feature is very useful for static websites, but for dynamic websites, it can only be said to be better than nothing (I have encountered this: when there was a problem with the WordPress origin server, some pages could open, but the layout and colors didn't look quite normal, so it can only be said to be better than nothing).
This feature is not dangerous and can be kept enabled.
Development Mode

Once this mode is enabled, all requests bypass CF's cache and go directly to the origin server. This feature is very useful when you need to see changes instantly. Once enabled, if not manually turned off, Development Mode will last for three hours and then automatically turn off.
Tiered Cache

Simply put, if this feature is not enabled, any CF data center around the world can directly initiate a request back to the origin server, even if that data center is very far from the origin server.
Once this feature is enabled, CF will divide global data centers into two tiers (upper and lower), and then use Argo performance and routing data to dynamically find a single optimal upper tier for the origin server (the optimal upper tier is closest to the origin server, theoretically offering the highest efficiency for fetching from the origin). Only the upper tier can initiate requests back to the origin server, while the lower tier can only query the upper tier.
This feature is not dangerous and can be kept enabled.
How to Verify Cache Status
Verification of Static Sites
For general static websites (taking www.tangwudi.com as an example) to verify the cache status, you can follow the process below.
Open Chrome browser (or Edge), press ”F12” to enter Developer Tools, click the ”Network” tab, and select ”All" for the type:

Enter in the browser address bar
www.tangwudi.comand press Enter, then right-click on the ”Reload” button and select ”Empty Cache and Hard Reload”:
Select on the left name side
www.tangwudi.com, and you can check if the cache is successful in the ”cf-cache-status” of the ”Response Headers” section on the right ”Headers” side:
Verification of Dynamic Sites
Taking my temporary test siteblog.tangwudi.xyzas an example:

Note 1: Generally, if Cache Rules (or Page Rules) are used to control CDN caching, cf-cache-status usually has 3 results: HIT (fully cached), DYNAMIC (partially cached, generally because no specific Cache Rules are configured and only CF's default caching rules are triggered, or because the keyword in the cookie matched the ”Bypass Cache” policy after logging into a dynamic website, so only a part is cached), BYPASS (bypassed, indicating that a cache rule is set to bypass the cache for this address).
Note 2: The above verification method is only suitable for verifying the caching effect achieved by conventional caching policies set through Cache Rules or Page Rules. It is not suitable for verifying the smart caching effect achieved using Workers or APO. The verification of the smart caching effect will be discussed in subsequent related tutorials.
Note 3: For dynamic websites (like WordPress), the conventional caching effect achieved using Cache Rules or Page Rules is similar to Hanamichi Sakuragi's ”commoner shot” in Slam Dunk. The effect is average, and it cannot leverage some of the advanced features available to CF Enterprise users, so it can only be said to be passable. To achieve an effect similar to a ”slam dunk”, you have to rely on Workers or APO, which will be covered in subsequent articles.
Afterword
Actually, I originally planned to write about ”Cache Rules, Redirects, and Page Rules” together in this article, because I thought there wasn't much to write about just Cache Rules, and it could be finished in a few sentences. However, I didn't expect to write more and more... so I had to write a separate article for it.
But thinking about it carefully, this is as it should be: for most people, the combination of WAF, DDoS, and Cache Rules can already solve the most common access and security issues. Therefore, if tutorials one, two, and three are the ”Foundation Building” trilogy, then four, five, and six can be called the ”Golden Elixir” trilogy. Knowing how to use them is enough to protect yourself in the world~.
I feel the cookie can be changed to wordpress_sec, so that as a blog owner, you can still see the cached interface after logging out. If set as above, the blog owner won't be cached as long as they click the login interface.
I haven't tested this in detail, but it is indeed possible. When I was testing using cache rules to cache WordPress, I did feel that accessing the backend was not fast, and sometimes there were some issues. I just didn't pay much attention to it because my usual management is to access WordPress directly for management, not through CDN cache (I have always recommended separating the way the WordPress site is accessed externally from the usual management method), so that the WAF policy can be set more strictly. Thank you for your suggestion, I will optimize the cache rule policy when I have time later.