Recommended Cloudflare Performance and Security Settings (Guide)

Cloudflare stands out as an impressive ally in the pursuit of optimal website performance and security. Known for its robust suite of tools designed to enhance website performance and bolster security, Cloudflare has become an essential component in the toolboxes of web developers and IT professionals alike.

However, harnessing the power of Cloudflare isn’t without its challenges. The platform offers a vast array of settings, each with its own impact and use case. Navigating the seemingly hundreds of settings can be a daunting task, particularly for those new to Cloudflare or less experienced in web optimization. This guide aims to demystify these settings, breaking down each one in terms of its 1) Function, 2) Benefit, and 3) Optimal Setting.

Note: Please note that I am not affiliated with nor am I compensated by Cloudflare for creating this guide. My insights and recommendations are based on professional experience and are intended to inform and assist those looking to enhance their website security and performance.

Recommended Cloudflare Performance Settings

Website speed can make or break user engagement, while security threats lurk around every corner. Cloudflare provides a layer of protection and efficiency that’s hard to overstate. From small blogs to enterprise-level websites, the impact of well-configured Cloudflare settings is profound. Providing improved page load times, enhanced user experience, and robust security.

As we embark on this journey of optimization, we will explore a range of Cloudflare’s features, starting with one of its most insightful tools: the Speed Observatory. This feature is a testament to Cloudflare’s commitment to not just providing tools for performance enhancement, but also offering the means to accurately measure and analyze it.

Cloudflare > Speed > Observatory

Cloudflare Speed Observatory

The Speed Observatory offers a comprehensive view of your website’s performance, laying the groundwork for informed decisions on configuration adjustments. It’s here that our journey into optimization begins. This tool is not just about speed metrics; it’s a gateway to understanding the performance of your website in a detailed and actionable way.

As an alternative, you can use pagespeed.web.dev which Cloudflare provides a link to as well.

  • Function: Monitors website speed and performance metrics.
  • Benefit: Identifies areas for improvement, encourages enhancement of user experience.
  • Optimal Setting: Enable the “Daily” testing feature.

Enable the "Daily" testing feature.

 

Cloudflare > Speed > Optimization

Cloudflare > Speed > Optimization

Cloudflare > Speed > Optimization is dedicated section in the Cloudflare UI that empowers users to apply a variety of image and protocol enhancements that work in concert to reduce load times and improve user experience. Let’s unpack these options:

Image Optimization

Polish

Automatically optimizes image loading by compressing pictures without sacrificing visual quality. Although I recommend enabling this setting, there’s no need to enable it if you are already serving images in optimized formats (AVIF & WEBP) from your origin server.

In my case, I’m serving images already optimized via my Nginx web server. However, in this case a paid account (Pro or higher) is still required. This is because the Cloudflare free plan does not support the Accept header (read: Vary for Images: Serve the Correct Images to the Correct Browsers by Cloudflare). Available “Vary for Images” in your Cloudflare plan is necessary to use Cloudflare CDN Caching when loading WebP and AVIF files from your origin server.

  • Function: Compresses images, strips metadata.
  • Benefit: Reduces image file size, speeds up loading.
  • Optimal Setting: Enabled + lossy compression for fastest speeds.
Mirage

Improves image loading on mobile devices and slow network connections. Replaces images with low resolution placeholder images that have the same dimensions as the original (including third party images).

Once the page renders completely, full resolution images are then lazy-loaded (prioritizing images in the browser viewport). This process allows pages to render quickly and minimizes browser reflow.

It also combines multiple individual network requests for images into a single request. Mirage also features lazy loading. I found this particually useful for the lazy loading of images on pages like: 100 Top Observability Tools (+ Server Monitoring and APM solutions) which has over 100 images.

  • Function: Lazy loads and virtualizes images.
  • Benefit: Enhances mobile and slow connection performance.
  • Optimal Setting: Enable for mobile-focused or image-heavy sites.

Protocol Optimization

HTTP/2

Utilizes the modern HTTP/2 protocol for improved loading efficiency over traditional HTTP. Don’t forget to make this improvement on your origin server as well. See this article: Enable HTTP/2 and HTTP/3 & QUIC on Nginx.

  • Function: Allows multiplexing, server push.
  • Benefit: Parallel resource loading, faster delivery.
  • Optimal Setting: Enabled, as it’s broadly supported.
HTTP/3

Enables the latest internet protocol, further enhancing speed and reliability.

  • Function: Introduces QUIC for reduced latency.
  • Benefit: Improves mobile network performance.
  • Optimal Setting: Enabled. Particularly for mobile users.
HTTP/2 to Origin

If the toggle is disabled, or your origin server does not support HTTP/2, Cloudflare will initiate a slower HTTP/1.1 connection to your orgin. As such, make sure to enable HTTP/2 on your orginal as per above link.

  • Function: Extends HTTP/2 benefits to origin server.
  • Benefit: Speed. Reduces connection overhead.
  • Optimal Setting: Enable if origin server supports HTTP/2.
Enhanced HTTP/2 Prioritization

With Enhanced HTTP/2 Prioritization enabled, resources will be delivered in the optimal order for the fastest experience across all browsers. See: Cloudflare blog post.

  • Function: Optimizes resource delivery order.
  • Benefit: Faster perceived load times.
  • Optimal Setting: Enabled. Especially for intricate resource loading.
Brotli

Implements Brotli compression for reduced file sizes and faster content delivery. See How does Cloudflare compress content?

  • Function: Compresses files more effectively than Gzip.
  • Benefit: Reduced file sizes, faster downloads.
  • Optimal Setting: Enabled.
0-RTT Connection Resumption

Enabling 0-RTT Connection Resumption allows for faster subsequent connections by permitting clients to send encrypted data to the server during the initial handshake, before the connection has been fully established. The “0-RTT” stands for “zero round-trip time,” meaning that data can be sent without waiting for the handshake to complete, which usually takes one full round-trip (1-RTT).

A security trade-off arises because this feature can potentially expose the connection to replay attacks. In a replay attack, an attacker intercepts the 0-RTT data and replays it to the server. Since the server accepts 0-RTT data without a completed handshake, it can’t be sure if the data was sent in a new connection or simply replayed by an attacker. This is because the data sent during the 0-RTT phase is not protected by the full TLS 1.3 handshake’s forward secrecy guarantees.

That said, the risk of such an attack may be acceptable compared to the performance benefits, especially for non-sensitive data. As such, only use 0-RTT for requests that do not change the state on the server if they were to be replayed (like GET requests in HTTP). For state-changing requests (like POST), it’s safer to wait for the full handshake to complete.

Also, read: Even faster connection establishment with QUIC 0-RTT resumption.

  • Function: Speeds up connections.
  • Benefit: Faster repeat visit load times.
  • Optimal Setting: Enable, with awareness of slight security trade-off.
Always use HTTPS

301 redirects all “http” traffic ti “https”.

  • Function: Redirects all traffic to HTTPS.
  • Benefit: Secures and potentially speeds up connections.
  • Optimal Setting: Enable, to leverage HTTP/2 optimizations.
TLS 1.3

Activates the most recent version of TLS, ensuring enhanced security and speed.

  • Function: Streamlines the TLS handshake process.
  • Benefit: Enhanced security, reduced connection time.
  • Optimal Setting: Enable for cutting-edge security and speed.

Tool Enhancements

Early Hints

Sends preliminary resource hints to browsers to initiate early page resource fetches. See Cloudflare’s blog annoucnement.

  • Function: Preloads critical resources early.
  • Benefit: Shortens time to first paint.
  • Optimal Setting: Enable, to anticipate resource loading.

The optimal settings provided above are general recommendations. The actual best setting may vary depending on the specific nature of your website, including your content, audience, and their typical connection types. It is always wise to test changes and monitor their impact through tools like Cloudflare’s Speed Observatory to ensure they are providing the desired benefits.

Cloudflare > Speed > Optimization enabled

By configuring each of these settings, users can significantly boost their website’s performance metrics. However, the key is not just to enable these features but to understand if they benifit to the specific needs of your website.

Cloudflare > Caching > Configuration

Cloudflare > Caching > Configuration

The Cache Configuration of Cloudflare UI is where you can tailor the caching behavior to optimize the performance of your website. Above you’ll see options for purging the cache, setting the caching level and browser cache TTL (Time to Live).

Purge Cache

This feature allows you to clear the cached content. Using “Custom Purge” enables you to selectively clear specific files or paths from Cloudflare’s cache, which is preferable because it allows you to remove only the outdated or changed content without affecting the rest of the cached data. On the other hand, “Purge Everything” clears the entire cache, forcing Cloudflare to refetch resources from the origin server, which will temporarily degrade your website’s performance.

  • Recommendation: Only use “Purge Everything” if there are substantial changes across the entire site that necessitate a complete refresh.

Caching Level

This setting determines how Cloudflare caches the static content of your site. The options are “No query string,” “Ignore query string,” and “Standard.” The “Standard” setting will cache resources based on the filename and query string, which works well for most websites.

  • Optimal Setting: “Standard” for typical use cases, adjusting as needed based on how your site uses query strings. That said, use custom rules to adjust sub domains, directories etc.

Browser Cache TTL

This setting specifies how long Cloudflare instructs a visitor’s browser to cache files. A longer TTL means that the browser will store the files for more extended periods, reducing the number of requests to Cloudflare’s servers.

  • Function: Directs the browser on how long to locally cache files.
  • Benefits: Reduces load times for repeat visitors and decreases bandwidth usage and server requests.
  • Optimal Setting: Respect existing headers. Or, adjust based on content update frequency—longer TTL for static content, shorter for dynamic.

No need to play around much with the other setting on this page. I usually enable “Always Online.”

Cloudflare > Caching > Tiered Cache Topology

Cloudflare > Caching > Tiered Cache Topology

The Tiered Cache Topology feature in Cloudflare is a sophisticated mechanism designed for optimizing content delivery by structuring the cache hierarchy across Cloudflare’s global network. This feature is particularly beneficial for websites with a global audience and static content, that need to manage their origin server’s load and bandwidth consumption efficiently.

Low traffic websites may not benefit significantly when enabling tiered caching, given the volume of requests may not be sufficient to justify the complexity or potential cost of a tiered caching system. The main advantage of tiered caching is reducing load on the origin server, which shouldn’t be a big concern for smaller sites.

Also, if the majority of the traffic is local, the content is already being served from the nearest data center, which minimizes the latency benefits that tiered caching can offer. Tiered caching is most effective when there’s high traffic coupled with a high cache hit rate from multiple regions. Small, local sites might not have enough traffic to populate the cache effectively across multiple points of presence.

Who Should Enable It

  • Websites with high traffic volumes and global reach should enable Smart Tiered Caching. It is especially useful for sites that serve a large amount of static content (like images, CSS, and JavaScript files) that can be cached and delivered quickly from a local data center.
  • Websites that frequently update content but still want to benefit from caching without overwhelming the origin with requests.

Who Should Leave It Off

  • Small websites with low traffic that primarily serve a local or regional audience may not see significant benefits.
  • Sites where content is highly dynamic and personalized, where caching would not be beneficial or might lead to stale content being served.

In essence, the cost-benefit ratio of enabling advanced caching features like Tiered Cache Topology may not be favorable for small, regionally-focused websites with modest traffic levels.

  • Function: Tiered Cache leverages Cloudflare’s regional data centers to cache content intelligently, reducing requests to the origin server.
  • Benefit: Reduces origin server load, saves bandwidth, and improves content delivery speed by serving from closer caches.
  • Optimal Setting: For high-traffic sites, enable Smart Tiered Caching to maximize cache efficiency and reduce latency. For smaller, low-traffic sites, or those with highly dynamic content, it may be optimal to disable it to ensure the most up-to-date content is served without unnecessary complexity.

Cloudflare > Traffic > Argo Smart Routing

Cloudflare > Argo Smart Routing

Argo Smart Routing is a Cloudflare service designed to improve the performance of web traffic delivery by intelligently routing visitors through the fastest paths across Cloudflare’s global network. By analyzing the conditions of the network in real-time, Argo chooses the most efficient route, avoiding congestion and reducing latency.

For an additional look at Cloudflare Argo, please read my blog post “Is Cloudflare Argo Worth It?” The article offers a nuanced look at how Argo’s benefits stack up against its costs. It’s evident that Argo can significantly enhance a website’s responsiveness, making it an asset for webmasters aiming to offer the best user experience possible.

  • Function: Argo Smart Routing dynamically selects the quickest paths for web traffic, reducing transit time.
  • Benefit: Minimizes latency (TTFB), improves load times, and enhances overall website performance.
  • Optimal Setting: Enable Argo for sites where speed is critical, and the audience is globally distributed; more beneficial for high-traffic sites where user experience is paramount.

Cloudflare > Rules > Page Rules

Cloudflare > Rules > Page Rules

Page Rules in Cloudflare allow you to customize Cloudflare’s settings on a per-URL basis. This flexibility can fine-tune the behavior of your website, improve security, and enhance performance for different sections of your site. Here’s an overview of the rules I have configured above:
(Note: these are specific for WordPress websites but can be tweaked accordingly.)

  1. The rule for static.domain.com/* is set to cache all content, with a long Edge Cache TTL (Time to Live) of one month. This rule ensures that all static assets (css, js, png, jpg, mp4, etc) served from this subdomain are cached by Cloudflare and kept for an extended period and regardless of query strings, thus reducing the load on the origin server and speeding up content delivery to users.
  2. Enhanced Security for Admin Area: The rule for domain.com/wp-admin/* increases the security level to High. This protects the WordPress admin area by adding additional security checks, helping to prevent unauthorized access and potential attacks.
  3. Under Attack Mode for Login: The rule for domain.com/wp-login.php* sets the security level to “I’m Under Attack,” which is a more aggressive form of protection. This mode challenges all visitors with a JavaScript computation check to filter out bots, protecting against brute force login attempts. Remember you should also set rate limiting not only via Cloudflare but also via Nginx or what ever web server you are using
  4. Under Attack Mode for Specific Paths: This rule applies to domain.com/connect/ or any webform being contactly abused by spam/malware bots. Set the security level to “I’m Under Attack.” This could be a response to specific threats or vulnerabilities associated with this path, necessitating heightened security measures.
  • Function: Each rule is designed to apply specific security or caching policies to different parts of a website based on the URL pattern.
  • Benifit: Enhances site performance by caching, secures sensitive areas, and protects against attacks in real-time.
  • Optimal Configuration: For static paths: “Cache Everything” (test compatibility/benefit) and a long TTL to maximize cache usage. For sensitive areas like admin and login pages: Increased security levels tailored to the perceived threat level. For areas under specific threat or high-security needs: “I’m Under Attack” mode to aggressively challenge traffic.

It’s important to note that the Page Rules should be ordered by priority, as the first matching rule will be the one that is applied. The configuration should be regularly reviewed and updated based on the evolving needs and threat landscape of the website.

Recommended Cloudflare Security Settings

Security threats are becoming increasingly sophisticated making it paramount for websites to fortify their defenses. The vast expanse of security features provided by platforms like Cloudflare offers a comprehensive shield, guarding against a multitude of threats ranging from opportunistic bots to coordinated DDoS attacks. Let’s review Cloudflare’s main security settings. Followed by the security events page, WAF (Web Application Platform), Bots and DDoS.

Cloudflare > Security > Settings

Cloudflare Security Settings

In the Security Settings of Cloudflare, you have the ability to adjust your website’s defense mechanisms according to the threat landscape and your specific security needs. The settings in the screenshot are critical components of Cloudflare’s security posture.

Security Level

This setting allows you to adjust the sensitivity of the security measures applied to your site. A medium level typically strikes a balance between protection and accessibility, challenging only the most suspicious traffic.

  • Function: Determines the threshold for challenging visitors.
  • Benifit: Balances user experience with security by filtering traffic based on threat level.
  • Optimal Setting: Set to medium for general use, higher during an attack, or lower for minimal interference with users.

Challenge Passage

This specifies how long a visitor has access to your website after passing a security challenge. It’s a way to ensure that once a user is verified as legitimate, they can browse without being challenged again for a set period.

  • Function: Sets duration of access post-challenge verification.
  • Benifit: Enhances user experience for verified visitors, reducing friction.
  • Optimal Setting: Set to 1 hour for most websites; adjust based on user behavior and threat intensity.

Browser Integrity Check

This feature scrutinizes HTTP headers from incoming requests to detect and block malicious threats, ensuring that only clean traffic reaches your site.

  • Function: Filters out malicious traffic based on header anomalies.
  • Benifit: Protects against common web threats and reduces malicious traffic.
  • Optimal Setting: Keep enabled to consistently safeguard against header-based vulnerabilities.

These settings form the first line of defense, offering a robust framework to protect your web assets while maintaining a seamless user experience. They are the groundwork upon which more specific and advanced security features are built, including WAF (Web Application Firewall), bot management, and DDoS protection, each of which we will explore next.

Cloudflare > Security > Events

Cloudflare > Security > Events

The Firewall Events dashboard in Cloudflare provides a comprehensive overview of security-related events affecting your website. It presents data and visualizations that give insights into the patterns and sources of threats. From the screenshot, we see different metrics like the number of events triggered by custom rules, security level settings, managed rules, rate limiting, and browser integrity checks.

The top section displays the quantity of events per service, offering a clear picture of which security features are most frequently engaged. All of which can be filtered by Action, Host, Country, ASN, IP, etc. This can help you understand the relative volume of threats and the effectiveness of your current security posture.

Cloudflare Top events by source

Below that, there’s a breakdown of ‘Top events by source,’ (see above screenshot) detailing the origin of security events, categorized by IP addresses, User Agents, paths, Countries, etc. This is crucial for identifying potential sources of attacks or malicious behavior. To recap:

  • Function: Provides real-time monitoring of security events, identifies patterns and sources of potential threats and enables targeted security responses.
  • Benifit: Assists in recognizing and responding to attacks swiftly, helps refine WAF rules and other security settings based on actual data and supports proactive measures against specific threats.
  • Optimal Setting: N/A (This is a monitoring tool, so there are no “settings” to optimize; instead, it informs the optimization of other security features.)

By monitoring the data presented in the Security Events section, administrators can make informed decisions to implement better WAF security settings. For example, if there is a high number of events from a particular country that does not align with your expected traffic patterns, you could create a Geo-Blocking rule in the WAF to mitigate this. Similarly, if certain user agents are consistently linked to malicious activities, they can be set up in the WAF to challenge or block them proactively. The goal is to use the insights gained from this dashboard to enhance your security posture continuously.

Cloudflare > Security > WAF (Web Application Firewall)

Cloudflare > Security > WAF (Web Application Firewall)
Improve your custom rules over time.

Cloudflare’s Web Application Firewall (WAF) is a robust security layer that safeguards websites and APIs from a myriad of threats, including cross-site scripting (XSS), SQL injection, and DDoS attacks. The WAF operates at the network edge, making it possible to detect and block potential attacks before they reach a site’s server. It’s an essential tool for any website looking to protect its data and maintain its integrity in the face of ever-evolving online threats.

The above screenshot shows some highlights the WAF’s user interface, with a particular focus on the “Custom rules” tab. This section allows for the creation of tailored rules that address specific security concerns. For example, the listed “Spam countries v2” and “Spam countries” rules suggest configurations designed to challenge traffic from regions known for generating spam or participating in malicious activities. Not all custom rules are visible in the screenshot, I will share the rest later. I recently changed domain names about 2 weeks ago so still setting up Cloudflare config for LinuxBlog.io.

Notice in the example above I’m adding instead of editing when making notable rule changes. Simply disable the previous version of the rule. Make use of your “available rules” so that you can quickly revert to previous rules if you need to. Don’t delete your previous rules until you run out of avaiable rules.

Cloudflare WAF Custom Rules Managed Challenge by country.
Custom rule to present a managed challenge. Ref: Cloudflare Security Level.

Cloudflare WAF Custom Rules events by country.
Managed challenges over a 30 minute period.

I blurred 5 of the countires, I just don’t want to encourage mass blocking of countries. Remember: Threats will differ from site-to-site. The best approach is to select countries based on your event logs. There are no bad countries that should always be singled out.

Custom rules

  • Function: Custom rules allow for precise control over how traffic is handled, letting administrators set criteria to challenge or block requests based on factors like country of origin, IP reputation and requests.
  • Benefit: These rules offer a granular level of security, enabling targeted protection against spam bots, automated threats, and specific vulnerabilities unique to your site. They are instrumental in preventing unwanted traffic and ensuring that resources are served to legitimate users only.
  • Optimal Setting: Custom rules should be tailored to the specific security needs of a site. The optimal setting varies based on the website/application, threat landscape and traffic patterns. It’s best to analyze traffic and threat reports to identify trends that warrant custom rules.

Here for example is a rule I use to block IPs that make requests to WordPress files that should not be accessed publicly. Remember even thought the file does not exist, for example, xmlrpc.php is deleted on our server but we still want to block IPs that request it. In any case here’s the custom rule:

(http.request.uri.path contains "/wp-login.php") or
(http.request.uri.path contains "/wp-register.php") or
(http.request.uri.path eq "/wp-admin/") or
(http.request.uri.path contains "/wp-admin/install.php") or
(http.request.uri.path contains "/wp-admin/upgrade.php") or
(http.request.uri.path contains "/wp-admin/theme-editor.php") or
(http.request.uri.path contains "/wp-admin/plugin-editor.php") or
(http.request.uri.path contains "/wp-config.php") or
(http.request.uri.path contains "/xmlrpc.php") or
(http.request.uri.path contains "/backup/") or
(http.request.uri.path contains "/wp-backup/")

Cloudflare Custom Rules WordPress URLs

Here’s a breakdown of the rule:

  • The rule uses the contains operator for several paths, such as /wp-login.php, /wp-register.php, /wp-admin/install.php, and others. This means it will block or manage access to requests that includes these specific strings.
  • The rule uses eq for /wp-admin/, which means it will only block requests that exactly match the /wp-admin/ path. This would not include /wp-admin/admin-ajax.php, or any other subdirectories like js/ or css/.
  • The action isn’t included in this rule. I suggest you skip, then challenge, then block after monitoring rules like this over several days or weeks.

Rate Limiting Rules

Cloudflare Rate-Limiting Rules

Rate Limiting Rules within Cloudflare’s Web Application Firewall (WAF) offer a robust mechanism for controlling the flow of traffic to your website or API. By setting thresholds for how many requests a user can make within a certain time period, rate limiting is essential for preventing abuse and ensuring that resources are not overwhelmed by excessive traffic, which could be indicative of malicious intent.

The above screenshot indicates two rules (Pro account limit): “WP Login” and “Flood.” The “WP Login” rule blocks excessive login attempts, protecting against brute force attacks on the WordPress login page. The “Flood” rule is currently set to issue a Managed Challenge instead of a block as I’m still in the testing phase. This is a approach is to ensure that legitimate users are not inadvertently blocked due to overzealous rate limiting. When implementing new rate limiting rules, it’s crucial to adopt a cautious and measured approach.

  • Function: Regulates the number of requests to prevent abuse and mitigates brute force and DDoS attacks.
  • Benifit: Preserves website and API availability and enhances security without affecting normal user access.
  • Optimal Setting: Initially set rules to Skip or Log to monitor impact. Use Managed Challenge as an intermediate step for testing. Proceed to Block only after confirming the rule’s accuracy and necessity.
Recommended approach when adding WAF rules

It’s important to monitor new rules carefully, starting with less restrictive actions like ‘skip’ or ‘log’. This allows you to gather data on the rule’s impact without disrupting user access. Managed Challenges can then be implemented to challenge suspicious traffic, which still allows access once the challenge is passed. This step is vital to fine-tune the rule’s sensitivity and to avoid false positives that could block legitimate users.

Only after thorough testing and assurance that the rule targets only the intended malicious or unwanted traffic should you consider escalating to a Block action. This progressive strategy ensures that security measures do not compromise user experience and that access is maintained for genuine traffic.

In the case of the “Flood” rule, this testing phase is particularly important. A week ago it was set to ‘skip’. It allows for the adjustment of thresholds and the evaluation of whether a challenge is an effective deterrent for the unwanted traffic observed. This careful approach to rule implementation is key to maintaining a secure yet accessible online environment.

Managed Rules

Cloudflare WAF Managed Rules

Managed rules within Cloudflare’s WAF serve as a comprehensive line of defense, automatically updated by the Cloudflare team to protect against emerging threats. The above screenshot highlights three key managed rules provided by default (Pro accounts and above):

  1. Cloudflare OWASP Core Ruleset: A set of rules designed to protect against widespread web application security risks as identified by the Open Web Application Security Project (OWASP).
  2. Cloudflare Managed Ruleset: Cloudflare’s own set of rules that protect against various exploits and vulnerabilities known to the Cloudflare community.
  3. Cloudflare Leaked Credentials Check: A safeguard that checks for credentials that have been exposed in known data breaches, helping prevent unauthorized access.

These managed rules analyze characteristics of each incoming request and determine the appropriate action to ensure the application’s security. However, applying these rules globally across your entire site can sometimes be overly restrictive, especially for areas of your site that are not sensitive.

Best Practices for Managed Rules Implementation

Cloudflare Best Practices for Managed Rules

To strike a balance between security and functionality, it’s often better to restrict the scope of managed rules to only cover areas of your site that are particularly sensitive, such as admin panels (/wp-admin/), file upload endpoints (/uploads/), and forms that submit sensitive information (web formd, login areas, checkout pages etc).

This targeted approach ensures that the rules are applied where they’re most needed, reducing the likelihood of false positives and unnecessary challenges to legitimate users. I’m not sure of the overhead involed, so I cannot speak to that but its probably best not to be have these rules enabled globably. For example, on your static directories and files. Feedback welcomed.

When first implementing managed rules, it’s recommended to set them to “Log” mode instead of “Challenge” or “Block”.  This allows you to observe the rules’ impact and gather data on potential false positives or legitimate requests that could be affected. The duration for this observation period can vary:

  • For high-traffic websites, up to a day of logging may suffice to collect a representative sample of data.
  • For low-traffic websites, a longer period may be necessary to ensure enough data is collected to make informed decisions about the rules’ configurations.

By monitoring the logs via the “Events” page, you can fine-tune the rules to minimize disruptions to user experience while maintaining robust security measures. Once you’re confident in the rules’ accuracy and efficacy, you can then transition from logging to enforcing actions like “Challenge” or “Block.”

WAF Tools

I’m still setting up the section and prefer to take screenshots a week or two after. So this section is coming soon. For now, “Tools” section of Cloudflare’s WAF includes some additional features that enhance the firewall’s functionality, allowing for greater control and customization of security settings.

  • IP Access Rules: Use these rules to block known malicious IPs or allow traffic from known good IPs. It’s important to regularly update these lists to adapt to changing traffic and threat patterns.
  • User Agent Blocking: Before creating blocking rules, analyze your site’s traffic to identify any user agents associated with suspicious behavior. Be cautious to avoid blocking legitimate crawlers like search engine bots.
  • Zone Lockdown: Implement lockdown rules for URLs that should only be accessed by your team or specific systems. This ensures sensitive areas are not exposed to potential attackers.

Cloudflare > Security > Bots

Cloudflare > Security > Bots

Cloudflare’s Bots feature provides insights and controls to manage automated traffic on your site, distinguishing between likely human visitors, automated bots, likely automated traffic, and verified bots, as seen in the screenshot.

The “Bot Report” breaks down the total requests into categories, showing that out of 85.59k requests, 6.87k were from automated bots, 68.11k were likely human, 3.37k were likely automated (but not definitively identified as bots), and 7.25k were from verified bots, which could include search engine crawlers and other beneficial bots.

  • Function: Identifies the nature of traffic, segregating human from bot activity.
  • Benefits: Enables targeted measures against malicious bots without impacting human or beneficial bot traffic.
  • Optimal Setting: Maintain a balanced configuration that blocks or challenges malicious bots while allowing verified and good bots necessary for SEO, performance obervability and website analytics.

The “Configure Super Bot Fight Mode” leads to more advanced bot management settings. Super Bot Fight Mode provides additional options for dealing with bots, but it should be used with caution. Overly aggressive settings might block legitimate crawlers which can negatively impact your site’s SEO and website visibility.

Cloudflare > DNS > Settings > DNSSEC

Cloudflare > DNS > Settings > DNSSEC

DNSSEC (Domain Name System Security Extensions) adds an extra layer of security to your domain’s DNS by attaching a digital signature to its DNS records. This signature ensures that visitors to your website are actually arriving at your real website, not a malicious one. Essentially, it helps to protect your domain against forged DNS answers, commonly known as DNS spoofing or cache poisoning, where an attacker redirects traffic from your domain to a fraudulent website.

  • Function: Secures DNS lookups with cryptographic signatures.
  • Benefits: Prevents DNS spoofing and ensures data integrity.
  • Optimal Setting: Enabled, with a properly configured DS record.

Cloudflare > SSL/TLS

Cloudflare > SSL/TLS

The SSL/TLS section in Cloudflare is where you configure the encryption for data transferred between the client (browser), Cloudflare, and the origin server. This, as you probable already know, enables the SSL certificate lock icon in your web browser.

“Full (strict)” mode ensures that the connection between both the browser and Cloudflare, and Cloudflare and the origin server, is encrypted. This mode requires a trusted certificate on the server, which means it must be signed by a recognized Certificate Authority (CA) or by Cloudflare Origin CA. It’s the most secure option because it verifies that the certificate on the origin server is valid before establishing a connection, preventing man-in-the-middle attacks. Also, read Cloudflare’s Encryption modes.

  • Function: Ensures end-to-end encryption with certificate validation.
  • Benefits: Provides strong security, preventing eavesdropping and tampering.
  • Optimal Setting: “Full” or better yet “Full (strict)” for maximum security with a valid SSL certificate.

Edge Certificates

Cloudflare Edge Certificates

The “Edge Certificates” section is pivotal for ensuring that your website is securely served over HTTPS. The screenshot above highlights two essential security features: “Always Use HTTPS” and “HTTP Strict Transport Security (HSTS).”

Always Use HTTPS

This feature enforces the use of HTTPS by redirecting all HTTP requests to HTTPS, ensuring that data between your users and Cloudflare is encrypted.

This setting is a fundamental step towards securing user traffic on your site. It is particularly useful for preventing users from accidentally accessing a non-secure version of your site. This setting is a best practice for all websites and should be enabled as part of a basic security posture.

  • Function: Redirects HTTP requests to HTTPS automatically.
  • Benefits: Guarantees secure, encrypted connections for all users.
  • Optimal Setting: Enabled, to ensure all traffic is secure by default.
HTTP Strict Transport Security (HSTS)

HSTS is a security policy mechanism whereby the web server declares that browsers should only interact with it using secure HTTPS connections.

HSTS further reinforces this security by ensuring that once a user has accessed your site, their browser remembers to always use HTTPS, not just for the initial request but for all subsequent requests for the duration specified by the max-age parameter. Including subdomains ensures that the HSTS policy is applied uniformly across your entire domain, and enabling preload tells browsers to enforce HTTPS even on the first visit before any interaction with your site.

When setting the max-age parameter for HSTS, it’s important to consider how often your site’s users visit and how likely you are to maintain HTTPS availability. A longer max-age increases security but requires a commitment to keeping your HTTPS infrastructure in good order. Preloading should be used with caution, as it commits your site to HTTPS permanently, which can be an issue if you ever need to revert back to HTTP. –>You’ve been warned!!<–

  • Function: Instructs browsers to only use HTTPS for all connections.
  • Benefits: Prevents SSL stripping and man-in-the-middle attacks.
  • Optimal Setting: Enabled with a long max-age (at least 6 months), include subdomains, and consider enabling preload for added security.

Cloudflare SSL/TLS settings

The features shown in the above screenshot are also critical for ensuring secure and efficient communication. Full disclosure, you can use “SSL/TLS Recommender” which will email you a recommended TLS minimum version. Or, take a look at the “Traffic Served Over TLS” bar and decide based on current active versions used to connect to your website. No matter what you use do not use TLS below version 1.2.

Minimum TLS Version

This setting dictates the oldest version of the TLS protocol that visitor connections must use to access your site.

  • Function: Sets the lowest acceptable TLS version for connections.
  • Benefits: Enhances security by using newer, more secure protocols.
  • Optimal Setting: TLS 1.2 or higher for a good balance between compatibility and security.
Opportunistic Encryption

This option allows HTTP/2 connections over TLS without altering the URI scheme to HTTPS in the browser’s address bar.

  • Function: Provides HTTP/2 benefits over encrypted connections.
  • Benefits: Improves loading times while maintaining encryption.
  • Optimal Setting: Enabled, to offer performance improvements of HTTP/2.
TLS 1.3

TLS 1.3 is the latest version of the TLS protocol, offering improved security and speed.

  • Function: Activates the latest TLS protocol for connections.
  • Benefits: Increases security and connection speed.
  • Optimal Setting: Enabled, to ensure the highest security standard.
Automatic HTTPS Rewrites

This feature helps to prevent mixed content issues by rewriting HTTP URLs to HTTPS automatically, where possible.

    • Function: Converts insecure links to secure ones on your site.
    • Benefits: Resolves mixed content issues, enhancing site security.
    • Optimal Setting: Enabled, to ensure secure content delivery.

These settings are crucial for safeguarding data in transit and ensuring that your website’s encryption protocols meet current security standards. By correctly configuring your edge certificates and related settings, you provide a secure environment for your users and improve their trust in your site.

Cloudflare > Security > DDoS

Not that automatic DDoS protection is always enabled by default and is constantly analyzing traffic, generating real-time signatures to mitigate attacks across the network and application layers. No action necessary. Feedback/tips welcomed.

Cloudflare > Security > Page Shield

Cloudflare > Security > Page Shield

Page Shield is a feature within Cloudflare’s security suite specifically designed for applications with significant JavaScript elements. It monitors JavaScript dependencies and alerts administrators to any changes, helping to prevent malicious code injections or unauthorized changes that could compromise a website’s integrity or user data.

  • Function: Monitors JavaScript dependencies for changes or anomalies.
  • Benefits: Protects against malicious script injections and data breaches and alerts administrators to unauthorized modifications.
  • Optimal Setting: Enabled for websites with heavy JavaScript usage for proactive security monitoring.

I’m not currently using Page Shield for my blog. However, the above screenshot is from one of my fully managed clients. Page Shield is particularly useful for websites that rely on JavaScript, as it ensures the integrity of the scripts running on the site. This is crucial for maintaining both website functionality and user security, especially when JavaScript is used to handle sensitive information or complex interactions.

Cloudflare > Security > Page Shield (list of active scripts)

For websites where JavaScript is a cornerstone of the user experience, having Page Shield enabled with vigilant monitoring is essential. The optimal setting for such sites would be to have Page Shield continuously monitor all JavaScript resources, with alerts finely tuned to the sensitivity of the content and the typical behavior patterns of the site’s users. This ensures a secure, uninterrupted browsing experience for users while preserving the site’s functionality and performance.

Conclusion

Cloudflare has even more features available in their Business and Enterprise plans.
Cloudflare Security Analytics page.

Cloudflare’s comprehensive suite of performance and security tools offers an invaluable resource for web developers and IT professionals striving to enhance their website’s speed, user experience, and protection. This guide has walked you through the intricacies of optimizing Cloudflare’s settings, highlighting the important role each feature plays in boosting website performance and securing it against an ever-evolving landscape of online threats.

Remember, while the recommended settings provide a strong starting point, the unique characteristics of each website demand a tailored approach. Regular monitoring and adjustments, informed by tools like Cloudflare’s Speed Observatory, Security Events, Google Pagespeed insights and observability are key to ensuring these settings continue to align with your site’s evolving needs and the changing digital environment.

By leveraging these capabilities, webmasters can not only meet but exceed the expectations of their users, delivering experiences that are both seamless and secure.

Tags: , , ,

Discussion

  1. That’s a really nice post, there’s a lot of settings and it can be super overwhelming for new people, over time you just get a feel for which ones are important.

    I would mention a few things though:
    Page Rules are dead (or dying)
    https://blog.cloudflare.com/future-of-page-rules
    There’s a bunch of new rules like Cache Rules, Config Rules, Redirect Rules, etc. You get more of them conbined, and they have more options and better matching. They can be a bit complex to use at first, as they don’t support wildcards and use the ruleset engine for expressions, but it’s totally worth it with how flexible they can be in matching and more options

    Most of the WAF Tools are old, super old. IP Access rules may be useful at times, although you can just do that in the WAF or with account IP Lists, but for allowing they’re no where near as granular as custom rule skips. Use CF Access rather then zone lockdown, allowlisting by IPs is annoying and outdated when you can use CF Access and sign in via Github/Google/etc for free to verify your identity.

    If you can disable all of the features like Automatic HTTP Rewrites you can prevent Cloudflare from needing to decompress and recompress your html: Content compression | Brotli · Cloudflare Speed docs
    I haven’t tested the performance difference but I’m assuming there’s some latency savings, plus a lot of a fair amount of issues/incidients have came from those tools like Automatic HTTPS Rewrites, Rocket Loader, etc. In my opinion if you don’t have any insecure links on your page that need to be rewritten (which you shouldn’t, you can always change them at your host), I would disable that, as well as most features which rewrite html.

    For SSL/TLS, Full (Strict) is the only secure option, it’s the same security as web browsers have. Full is accepting any certificate, even self-signed as it mentions, so if someone MITM’d the connection to your origin they could just serve any certificate and all you’d acheive is encrypting the request to the attacker…

    Cloudflare under SSL/TLS → Origin Server offers Certificates trusted by the Cloudflare Proxy, which work with Full (Strict) and last up to 15 years, no excuse for not using Full (Strict)!

    Argo Smart Routing is super cool and gives you “Enterprise like” inbound routing and faster outbound routing to your origin. The inbound part can help in regions like Asia-Pacific where you may not otherwise be routed to some cf locations on free or pro.

    Anyway nice post!

    If there’s one thing I hope someone new to Cloudflare would learn, it’s to not use Flexible, Full (Strict) with Origin Cert or publicly trusted like Let’s Encrypt via Certbot. By far the #1 wrong security thing I see, and it’s so easy to mess up since Cloudflare defaults to Flexible :frowning:

  2. Hi @Chaika I recognized your username immediately from Cloudflare Community. I’m pretty sure you have helped me there more than once in the forums.

    I do appreciate the feedback! Reading through it now…

    Your above comment will be posted right below the blog post itself, so it will be useful for others as well, I’m sure.

    Noted on page rules. I’ve become so used to them over the years that I definitely have been slow with the change, or rather the upgrade. I will convert my rules and then update the article.

    Oh! This is interesting! I did not know that. I’m also using Rocket Loader. Do you think the performance gained by disabling Automatic HTTPS Rewrites and Rocket Loader will be more than the -200 ms improvement with Rocket Loader enabled? I guess there’s only one way for me to find out eh. :slight_smile:

    Will do, yes there is no insure/http stuff via origin. I’ve tried to config Nginx to be close to CF. So not sure why I didn’t think of disabling.

    Noted. Was not aware of this either.

    Its great, requires no config either. If one can keep their data transfer sizes down its really of good value.

  3. Hey! Happy to help :slight_smile:

    If it genuinely shaved off 200ms then no way would the latency savings from not recompressing beat that. Rocket loader is an iffy one though, it has some compatibility issues and is a tool for “the old web”. It’ll help in cases where sites have a ton of non-dependent scripts, and/or stuff could be deferred/async. But you could do that yourself, and in cases of modern javascript framework builds like React/Vue/etc, they’ll do that as much as they can for you already and Rocket Loader can only slow them down/break things.

    It’s not even part of Cloudflare’s new Speed Tab recommendations anymore

    Yea the new rules are super cool! Writing your own expressions rather then using the Expression Builder enables you to do a lot as well, the Ruleset Language they use is based on the Wireshark filter language.

    You can do a lot more with one of the new rules then with a single Page Rule, ex:

    I would always break down your expressions at much as possible and avoid using the larger fields like URI Full, less fragile and easier to change in the future that way.
    There’s docs on each field here: Fields reference · Cloudflare Ruleset Engine docs

  4. I’ll note it here for anyone else using WAF for added WordPress security. After reading docs I’ve updated the rules to:

    – Block requests that are attempting to access various sensitive WordPress paths like xmlrpc.php, wp-admin, and others. But excludes (does not apply the rule) if the referer is your own site (in this case, “linuxblog.io”):

    (http.request.uri.path in {"/wp-register.php" " /wp-admin/" "/install.php" "/theme-editor.php" "/wp-config.php" "/backup/" "/wp-backup/" "/upgrade.php" "/xmlrpc.php"} and not http.referer contains "linuxblog.io")
    

    Something is also setup on the local server which will block locally and then add the IP to Cloudflare WAF as well.

    For the country filtering:

    (ip.geoip.country in {"XX" "XX" "XX"} and cf.threat_score ge 5) or (http.request.uri.path contains "/wp-login.php")
    

    (ip.geoip.country in {“XX” “XX” “XX”} and cf.threat_score ge 5) or (http.request.uri.path contains “/wp-login.php”)

    Replace “XX” with the country or countries you require and set threat score based on this.

    I know fail2ban isn’t the most eligant solution, but using Fail2Ban with Cloudflare API to add server blocks to Cloudflare:



Top ↑