Introduction
This guide provides non-exhaustive recommendations and general best practices to achieve a comprehensive Layer 7 (L7) / Application Security approach with Cloudflare.
This may be relevant for those seeking similar frameworks, such as CIS Benchmarks.
Some features mentioned are available only through advanced Cloudflare bundles, such as WAF Advanced, Advanced Rate Limiting, or Enterprise features like Enterprise Bot Management.
This guide assumes that your domain is already onboarded to Cloudflare as a Zone and configured using Full Setup, meaning Cloudflare is acting as your authoritative DNS provider. Additionally, it’s recommended to have DNSSEC enabled and being familiar with Zone Holds.
You can find all recommendations, security rules and more in the Cloudflare L7 Best Practices Repository (Database) for quick searches.
Prerequisite Knowledge
Before implementing any of the recommendations below, it helps to be familiar with a handful of Cloudflare fundamentals. Most “why did my rule not match?” or “why is this request still reaching my origin?” situations trace back to one of the following concepts.
Order of Execution (Phases)
Cloudflare products do not all run at the same moment. Each product powered by the Ruleset Engine executes within its own phase, and phases run in a fixed order of execution.
Practical implications:
- Anything produced in a later phase cannot be matched in an earlier one. This is exactly why the
CF-Workerheader cannot be used in WAF Custom Rules (see Mitigate Unauthorized Cloudflare Workers), and why headers added by Request Header Transform Rules are invisible to the WAF. - A Skip action only skips the products or phases you explicitly select. It is not a global “allow everything”, and it cannot undo a phase that already executed.
- Within a phase, rules are evaluated top to bottom and the first terminating action wins. Order matters: narrow Skip / Allow rules at the top, broader mitigations below.
- Response phases (Custom Errors, Managed Transforms, Response Header Transform Rules, Compression Rules, and Rate Limiting Rules that use response information) only run after the origin has responded.
Reference: Phases list and WAF phases.
HTTP/S Network Ports
Cloudflare’s proxy only handles a specific set of HTTP/S ports: 80, 8080, 8880, 2052, 2082, 2086, 2095 for HTTP, and 443, 2053, 2083, 2087, 2096, 8443 for HTTPS. Requests to any other port on a proxied hostname are not handled by Cloudflare’s proxy by default. For that you’d require Spectrum.
- Caching is disabled on the alternative ports (
2052,2053,2082,2083,2086,2087,2095,2096,8880,8443), unless an Enterprise cache rule enables it. - Only ports
80and443are compatible with the China Network. - To prevent HTTP/S requests over non-standard ports from ever reaching the origin, enable the Anomaly:Port - Non Standard Port (not 80 or 443) rule described in Stricter Security Requirements with WAF Managed Ruleset.
- For anything that is not HTTP/S (i.e. SSH, RDP, custom TCP/UDP), use Spectrum rather than gray-clouding / DNS-Only the DNS record, which would expose the origin IP. See Non-HTTP/S Use Cases.
- Because of Cloudflare’s anycast network, port scanners will likely report these non-standard ports as open on Cloudflare IPs. That is shared Cloudflare infrastructure serving many customers, not an open port on your origin.
TCP Connections and Connection Limits
When traffic is proxied, there are two independent TCP connections: client → Cloudflare, and Cloudflare → origin. Each has its own timeouts and connection limits.
- Client-side connections have a 400 second idle timeout, after which Cloudflare sends keep-alive probes and eventually severs the connection with a TCP Reset (RST).
- Origin-side timeouts map directly to the Cloudflare error your users would see: 522 (complete TCP connection at 19s, or TCP ACK timeout at 90s), 520 (keep-alive interval at 30s, or proxy idle timeout at 900s), and 524 (proxy read timeout at 125s — configurable for Enterprise zones — or proxy write timeout at 30s).
- Ensure HTTP keep-alives are enabled on your origin. Cloudflare reuses open TCP connections, and origins that close them aggressively cause avoidable connection resets.
- Smart Shield extends this with connection reuse, batching requests from upper-tier data centers over shared connections and reducing origin connections by roughly 30% on average. This lowers the risk of connection exhaustion at the origin under high traffic.
- URLs are limited to 16 KB, and request and response headers to 128 KB in total. Oversized headers (i.e. large JWTs or cookie jars) are rejected before your rules ever evaluate them.
- Applications should handle disconnections gracefully: capacity balancing, data center maintenance, or node restarts can end a connection even with keep-alives in place.
Note: some TCP connection settings can be customized for Enterprise customers — reach out to your account team.
Cloudflare HTTP Headers
Cloudflare adds, modifies, and removes a number of HTTP headers on proxied traffic. Knowing which is which avoids both broken origin logic and false confidence in spoofable values.
CF-Connecting-IP— andTrue-Client-IPon Enterprise — carry the original visitor IP to the origin. Many prefer them overX-Forwarded-For, which may contain a chain of proxy IPs. Remember to restore original visitor IPs at the origin, otherwise every request appears to come from a Cloudflare IP.CF-Rayis sent to the origin and returned to the visitor, and is the single most useful value when correlating logs or contacting support.CF-Workeridentifies the zone originating a Workers subrequest, but is added after rule evaluation — match oncf.worker.upstream_zoneinstead.Cf-Mitigatedsignals to the client that a request was challenged, which is what makes challenge handling viable for API / AJAX / XHR requests.- Cloudflare may strip a few response headers (
Alt-Svc,X-Accel-*) and may drop request headers with names considered invalid, such as those containing a.(dot) character. - If you do not want visitor IPs forwarded at all, enable the Remove visitor IP headers Managed Transform.
_Note: any header a client sends can be spoofed. Headers added by Cloudflare are only trustworthy at the origin if the origin is locked down to accept traffic exclusively from Cloudflare — see Origin Server Protection.
The /cdn-cgi/ Endpoint
Every proxied domain gets a Cloudflare-managed /cdn-cgi/ endpoint, which cannot be modified or customized. Several products depend on it:
/cdn-cgi/trace— identify the Cloudflare data center serving a request./cdn-cgi/challenge-platform/— Challenges, JavaScript Detections (JSD), and Turnstile./cdn-cgi/image/— image transformations./cdn-cgi/l/email-protection— email address obfuscation./cdn-cgi/rum— Web Analytics.
Recommendations:
- Exclude
/cdn-cgi/from your security rules. Blocking or challenging it breaks Challenges, JSD, and Turnstile, and is one of the most common self-inflicted false positives. - Omit it from vulnerability scans, since some of these endpoints intentionally do not carry certain settings.
- Add
Disallow: /cdn-cgi/to yourrobots.txt, preceded byAllow: /cdn-cgi/image/if you serve transformed images.
Reference: Interaction between Cloudflare challenges and Rules features.
Error Responses
When Cloudflare cannot complete a request, it generates its own error response. This covers all 1xxx error codes and Cloudflare-generated 5xx errors (500, 502, 504, 520-526). 5xx errors generated by your origin server are passed through untouched.
The format follows the client’s Accept header: HTML by default, structured JSON for application/json or application/problem+json, and Markdown for text/markdown. Structured error responses are available.
Why this matters for security:
- API clients and agents receive parseable errors instead of an HTML page they cannot interpret — relevant whenever a mitigation lands on a non-browser client.
- Custom Errors take precedence. An uploaded Error Page is served to every client regardless of
Accept, while Custom Error Rules can match on theAcceptheader, letting you serve JSON to APIs, Markdown to agents, and branded HTML to browsers from the same zone. See Branding.
Note: keep error content generic. Verbose error output leaks stack traces, origin hostnames, and framework versions.
Note: if you intend to validate any of the configurations below with a scanner or a penetration test, first review the Scans and Penetration Testing Policy.
Troubleshooting
- Review the Cloudflare Status page.
- Consult the Troubleshooting section.
- Gather necessary information and contact Cloudflare Support.
- Use Trace to understand the impact of your Cloudflare configurations on specific requests.
Recommendations
In general, in most cases you can create rules with the action set to “Log” for testing purposes. This allows you to review what it matches in the Security Events and fine-tune it as needed before applying a more impactful action, such as “Block”, “Managed Challenge”, or even “SKIP”.
For more information, review the older article Protecting OSI layers.
Rollout Approach and Choosing an Action
Whatever the signal, the safest way to introduce it follows the same progression:
Baseline in Security Analytics / Bot Analytics → log-only where supported →
limited challenge or rate-limit → enforce → monitor false positives →
tune thresholds and exceptions
Then pick the action that matches your confidence in the signal and the cost of a false positive:
| Action | Use when | Avoid when |
|---|---|---|
| Log / simulate | New signal, uncertain impact, customer is baselining | A confirmed active attack is harming the origin |
| Skip | Narrow, known-good traffic needs to bypass a specific security control | Broad bypasses for whole ASNs, countries, or generic bot categories |
| Managed Challenge | Browser traffic is suspicious but may be legitimate | API clients, mobile apps, or machine-to-machine flows that cannot solve browser challenges |
| Interactive Challenge | High-risk browser flow where user friction is acceptable | Conversion-critical flows unless scoped narrowly and monitored |
| Rate Limit | Volumetric abuse, credential stuffing, carding, scraping, API abuse | Solely by IP address for mobile/CGNAT-heavy audiences |
| Block | Confirmed malicious fingerprints, impossible flow, known exploit, or repeat abuse | Ambiguous traffic where false positives would be costly |
| Serve cached content | Public cacheable pages during scraping or traffic spikes | Personalized content, checkout, login, account, admin, or sensitive API responses |
_Note: Skip bypasses the specific Cloudflare products or phases you select and nothing else.
WAF Managed Rules
Deploy WAF Managed Ruleset
It’s widely recommended to briefly review and then deploy the Managed Ruleset across the entire Zone. Create specific exceptions, if required.

Note: that it is not recommended to have both Account-level WAF Managed Rules, as well as Zone-level WAF Managed Rules deployed and enabled at the same time as this could lead to confusion when reviewing the Security Events. Preferably, standardize at account level with the Account-level WAF Managed Rules; avoid duplicating the same ruleset at the zone level unless you need zone‑specific overrides.
Reference: Cloudflare Managed Ruleset.
Stricter Security Requirements with WAF Managed Ruleset
For additional and stricter security requirements, deploy some of the following rules:
- XSS, HTML Injection with Rule ID 882b37d6bd5f4bf2a3cdb374d503ded0.
- Anomaly:URL:Path - Multiple Slashes, Relative Paths, CR, LF or NULL with Rule ID 6e759e70dc814d90a003f10424644cfb.
- Anomaly:Body - Large with Rule ID 7b822fd1f5814e17888ded658480ea8f, in order to mitigate body payloads which are higher than the processing limit.
- It is generally recommended to add WAF exceptions for this, especially for upload endpoints.
- Anomaly:Port - Non Standard Port (not 80 or 443) with Rule ID 8e361ee4328f4a3caf6caf3e664ed6fe.
- Anomaly:Method - Unusual HTTP Method with Rule ID ab53f93c9b03472ab34a5405d9bdc7d5.
- Anomaly:Method - Unknown HTTP Method with Rule ID 6e2240ffcb87477bbd4881b6fd13142f.
- Including all the Vulnerability scanner activity-related Rules.
- Any other relevant Rules you might need.
Log the payload of matched rules, if required, to help diagnosing the behavior of the rules. The encrypted payloads can be found in the Metadata field in Firewall events logs.
Note: it is also generally recommended to disable (globally or selectively) Browser Integrity Check (BIC), especially to prevent potential false positives with APIs / automated traffic and non-browser endpoints. Use modern detections like WAF Managed Rules and Bot Management instead.
Reference: Security Events and Changelog.
Deploy OWASP Core Ruleset
If required, review and then deploy the OWASP Core Ruleset.
Note: Those types of rules are prone for false positives. For customers also using Zaraz, it is recommended to configure an exception for the configured Zaraz endpoint.

Reference: Handle false positives / Troubleshooting.
WAF Custom Rules
Custom rules give you granular control to tailor your security policy to your application’s specific needs. Rules are executed in order / phases, so place your most important rules at the top.
Allow Verified Bots
It’s ordinarily recommended to have as one of the first top Custom Rules a SKIP Custom Rule, allowing Verified Bots, such as i.e. Search Engine Crawler (like GoogleBot).

Reference: Verified Bots
Allow APIs
It’s generally recommended to have as one of the first top Custom Rules a SKIP Custom Rule, allowing your and/or partner APIs (i.e. payment callbacks, PreRender IO, etc.), being as specific and using as many fields as possible. The ultimate goal is to pursue a positive security model by implementing API Shield.

Reference: API Shield.
Redirect to Custom HTML
Using a Custom HTML response type, one can create a redirect to another site for specific requests. In this example, any non-verified bot requests coming from the US are redirected.

Block Fallthrough API Requests
In order to truly enforce a Positive Security Model, for any fallthrough action of requests not matching any of the API Shield-managed endpoints, create a WAF Custom Rule similar to the one below, preferably with more specific fields to your API.

Reference: Schema Validation.
Visibility into Non-expected Request Methods
In some cases, you want to be specific about what type of HTTP Request Methods are allowed on certain endpoints or coming from specific requests, or even just logging relevant methods for visibility.

Reference: HTTP Method Field.
Mitigate likely Malicious Payloads
Every HTTP/S request receives a WAF Attack Score (WAF ML), indicating the likelihood of containing something malicious related to SQLi, XSS, or RCE attacks. This should be used to complement existing security rules and serve as an additional signal to help mitigate potential attacks.

Reference: WAF attack score.
Mitigate known Open Proxies, Anonymizers, VPNs, Malware, and Botnets
By using the Cloudflare-Managed IP Lists, including your own Custom Lists, you can decide what to do with those IP categories. Generally, one wants to block Botnets and Malware.

Reference: Managed IP Lists.
Note: If you wish to manually block VPNs, here’s a list of ASNs commonly associated with popular VPN providers:
AS62041, AS202420, AS20473, AS23966, AS36352, AS14061, AS209854, AS20001, AS20115, AS32934, AS16276. This information might change and illustrative only.
Mitigate Tor Traffic
In case that Tor traffic – an overlay network for enabling anonymous communication – is unwanted, one can simply mitigate it. Make sure to also disable Onion Routing in this case.

Reference: Onion Routing and Tor support.
Mitigate unwanted ASNs
Any unwanted traffic coming from Cloud ASNs (such as AWS, Azure, GCP, etc.) or other ASNs from which you don’t expect traffic, you might want to mitigate. Use Lists with ASNs to easily manage these. One can also opt for dynamic Managed IP Lists.

Reference: Custom Lists.
Block High Risk Countries
Block high risk countries like the ones that appear in The Office of Foreign Assets Control (OFAC) List.

References: Sanctions List Search and OpenSanctions.
Block known Bot User-Agents
Block unwanted requests of user-agents known to be used by bots, such as cURL, go-http-client, or even empty user-agents.

Reference: Challenge bad bots.
Restrict WP Admin Dashboard Access
If you are using WordPress, restrict access to the /wp-admin to only specific static source IPs of employees or admins, or alternatively opt for a Zero Trust approach with Cloudflare Access.

Reference: Allow traffic from IP addresses in allowlist only.
Restrict Access to Employees Only
If you have employee portals or extranets, restrict access to countries in which you have employees located, or preferably opt for a Zero Trust approach. Try to be as specific as possible using multiple conditions like HTTP Header, ASN, and HTTP method.

Another alternative is to take advantage of mTLS, only allowing access to employees with valid client certificates.
Reference: Allow traffic from specific countries only.
Mutual TLS Authentication
Block all requests that do not have a valid client certificate for Mutual TLS (mTLS) authentication on a specific hostname. In this scenario, mTLS refers to the connection between the client and Cloudflare.

Additionally, another consideration is to also check if the Client Certificates, generated with the default Cloudflare Managed CA, have been revoked and block those.

References: Cloudflare Public Key Infrastructure (PKI), CFSSL, API Shield mTLS and Workers mTLS. Check out this Learning Path on mTLS at Cloudflare.
Another interesting use case is to associate specific mTLS hostnames with Client Certificate Serial Numbers (cf.tls_client_auth.cert_serial). This allows for more granular control.

User-Specific JWT Claim Mitigation
To enhance the security of your API endpoints that rely on JSON Web Tokens (JWT), you can create rules targeting specific JWT claims, such as the user claim.
In this example, requests from admin users based on the user claim are subjected to additional scrutiny by challenging requests flagged as potentially malicious based on their WAF Attack Score.

Reference: Issue challenge for admin user in JWT claim based on attack score and API Shield.
Visibility into Automated Bot Traffic
In general, one wants to have visibility into automated traffic. This can be commonly achieved with a LOG action, logging anything with a Bot Score “likely automated” based on available detection engines.

Reference: Bot Management variables.
Mitigating Pretend-Browsers with JavaScript Detections
In scenarios where the BotScore alone may not reliably differentiate between likely human and bots, you can enhance detection by optionally enabling JavaScript Detections (JSD).
Note: JSD can only be applied to HTML responses (
Content-Type: text/html) and it cannot be at the root/first HTML request as the JavaScript needs to be injected first.
When enforced via cf.bot_management.js_detection.passed rules and a Managed Challenge, JSD ensures active verification checks.

Note: Test with a logging action before enforcing rules to avoid impacting legitimate traffic. Additionally, the Rule should only apply on critical paths and not on initial landing pages, where JS might have not been injected yet.
Reference: Enforcing execution of JavaScript detections.
Visibility into IPv6 IPs
Most web applications want to be available via IPv6 IP addresses. However, in case that IPv6 is undesired, customers can mitigate IPv6 IPs through the WAF and also disable IPv6 compatibility, if needed.
Note: that this will also block Cloudflare Workers scripts. In order to allow Workers, review the Mitigate Unauthorized Cloudflare Workers section.

Reference: IPv6 compatibility.
Account Takeover (ATO) Detections
To detect and mitigate predictable bot behavior, such as login failures, one can use Detection IDs. This is also available for Rate Limiting Rules.

Reference: Account takeover detections and Turnstile.
Mitigate Disposable Emails on SignUps
To prevent users from signing up with known disposable emails, Cloudflare’s Disposable Email Check can easily check this behavior and the customer can decide what to do with this: block, challenge, log, rate limit, or even add a request header for the origin server.

Reference: Cloudflare Fraud Detection.
Mitigate Authentication Requests
Prevent or trigger a different behavior when a user tries to log in (authentication event) with leaked credentials, as per Have I been Pwned (HIBP). Or use different related fields.

Note: Authentication events (
cf.waf.auth_detected) refers to authentication credentials detected in a request with a status code 2XX.
Reference: Leaked credentials detection.
Time-based Rules
Time-based rules can leverage the http.request.timestamp.sec field to apply logic based on specific time periods (useful for maintenance windows or scheduled security posture changes).
For example, you could block all POST or PUT requests to a particular endpoint during a defined time frame.

Or simply Log or Skip (allow) specific requests for a specific time.
Note: The timestamp is represented in UNIX time (epoch time) and consists of a 10-digit value.
Reference: Configure a rule with the Skip action.
Mitigate Unauthorized Cloudflare Workers
The CF-Worker request header identifies the originating host of a subrequest made by a Cloudflare Workers Subrequest, such as when using the Fetch API.
Do not use CF-Worker in WAF Custom Rules, as it is added after rule evaluation. Instead, use cf.worker.upstream_zone, which holds the same value.
Block a specific Worker:
cf.worker.upstream_zone eq "example.com"
Block all Worker subrequests except from your own Worker:
not (cf.worker.upstream_zone in {"" "your-zone.com"})

Reference: CF-Connecting-IP in Worker subrequests.
More Common Use Cases for Custom Rules
Review the get started guide and the common use cases for custom rules for more examples. Additionally, for some use cases or if you are managing many Zones, the Account-level WAF can be a good feature to have.
Moreover, monitor and replace insecure JS libraries used in your applications.
Review all the fields reference.
Rate Limiting Rules
Rate limiting is essential for protecting your application from brute-force attacks, denial-of-service, and other forms of abuse.
IP-based Rate Limiting for Logins
To protect login endpoints from multiple login attempts from the same IP address, rate limit based on the required characteristics.

Reference: Rate limiting parameters.
Rate Limiting Uploads
To prevent too many uploads / HTTP requests using POST / PUT / PATCH methods.

Reference: Standard fields.
Rate Limit Credential Stuffing
To protect against credential stuffing attacks, it’s generally recommended using a layered-security approach. This rate limiting rule is but one example of several approaches.

Reference: Protecting against credential stuffing and Find an appropriate rate limit.
Rate Limit Suspicious Logins
Implement rate limiting for suspicious login attempts (authentication events) using leaked credentials, specifically leaked passwords, as per Have I been Pwned (HIBP).

Reference: Leaked credentials detection.
Geography-based Rate Limiting
If there are markets from which one does not expect a lot of traffic coming from in general, one could rate limit requests coming from those countries based on IPs or other characteristics.

Reference: Enforcing granular access control.
IPv6-based Rate Limiting
To protect against entire IPv6 Prefixes, rate limit with the custom characteristics using the cidr6 function and specifying the prefix length.

Reference: Rules language.
Client Certificate-based Rate Limiting
Rate limit based on the same Client Certificate being used multiple times over a specific period of time, in order to prevent abuse of potentially compromised certificates or devices. This is part of mTLS protection.

Reference: SHA-256 fingerprint of the certificate.
JavaScript Detection-based Rate Limiting
Use JavaScript Detections (JSD) to identify human-like clients by solving a challenge in subsequent HTML requests, flagged as cf.bot_management.js_detection.passed. Since JSD cannot run on the first HTML request, track failed JSD attempts on subsequent HTML responses (Content-Type: text/html) and block or challenge clients i.e. after 5 consecutive failures within a 10-minute window.

Reference: Do the Challenge actions support content types other than HTML (for example, AJAX or XHR requests)?.
Cookie-based Rate Limiting
In order to limit the amount of times a cookie can be used, one can rate limit by its characteristics. For example, rate limit session cookies or limit the amount of times a single cf_clearance cookie can be used.

Note: Challenge Passage can be lowered to 15 minutes to prevent re-usage by bots. Nonetheless, normally one should set the Challenge Passage to the user session time of 90-95% of users. For example, if users normally stay 6 hours on your website, set the Challenge Passage to 8 hours, in order to avoid a second challenge during a user session.
Reference: Cloudflare Cookies.
More Common Use Cases for Rate Limiting Rules
Review the rate limiting best practices for more examples.
Review all the fields reference.
Turnstile
Cloudflare’s Turnstile is a privacy-preserving CAPTCHA alternative that allows challenges anywhere on your site. It runs in standard browsers, including mobile – even native mobile apps – when using WebView. Implicit rendering auto-loads on static pages, while explicit rendering offers control over when and where it appears, ideal for dynamic content or Single-Page Applications (SPAs). Learn more about the differences here.
Enterprise customers can also take advantage of Ephemeral IDs, which can help track bots over longer time periods and rate limit based on these IDs instead of IPs or other characteristics.
Note: While Turnstile can be run in invisible mode, it is recommended to use managed mode for login and signup forms to provide users with a clear indication that an action is taking place. Alternatively, another option is to set it up with interaction-only. Additionally, the Turnstile Siteverify API should be triggered when the user clicks the button, initiating the POST request; (or while / before the user is already filling out the form).
When integrating on mobile, address common issues like WebView configuration and JavaScript interface to ensure smooth functionality.
It is also suggested to integrate Turnstile with WAF and Bot Management.
API / AJAX / XHR Requests
For API protection (AJAX/XHR requests), avoid using Challenges directly. APIs cannot complete interactive challenges, and browser CORS (Cross-Origin Resource Sharing) restrictions prevent smooth handling.
Instead, deploy Turnstile on high-risk frontend pages (e.g., login, checkout) to issue a cf_clearance cookie. Once issued, the cookie allows subsequent API requests to pass WAF evaluation without triggering challenges, preserving both security and usability.
For native or non-browser clients, consider detecting Challenge Page responses and handling them at the application layer.
If Managed Challenge wants to be applied directly to API endpoints, configure Transform Rules to expose the mitigation status by adding CORS:
Access-Control-Allow-Origin: *Access-Control-Expose-Headers: Cf-Mitigated
This enables clients to read the Cf-Mitigated header and adjust behavior accordingly.
Page Shield
Monitor your application’s JavaScript dependencies and get notified of any changes with Cloudflare Page Shield.
In general, you would want to periodically monitor resources and cookies running on your application. This is relevant for PCI DSS compliance.
Create Policies to enforce a positive security model, allowing only specific resources.
SSL/TLS Certificates
It is typically recommended to use the Advanced Certificate Manager (ACM) for features like delegated DCV, custom hostnames, total TLS, and Automatic SSL/TLS.
For customers with stricter requirements, additionally, disable the Universal SSL certificate.
Those seeking PCI compliance and granular customization over cipher suites should review the developer documentations, as well as the features TLS 1.3, Minimum TLS Version (TLS 1.2 is the recommended minimum, TLS 1.3 preferred), Automatic HTTPS Rewrites, Always Use HTTPS (or preferably disable HTTP plaintext altogether using HSTS).
Note: Review the Post-Quantum Cryptography (PQC) documentation for quantum-resistant algorithms.
Additionally, it is recommended to configure the origin server to match on origin.
Verify that there’s always a valid and active Edge Certificate for your Zones at all times.
Moreover, enabling HTTP/2, HTTP/3 (QUIC), and HTTP/2 to Origin are performance-related features, but also good for improved security.
Branding
In case that branding is important to you and your business, you are able to use and configure Custom Errors.
Additionally, for the Cloudflare WAF, you are able to configure a custom response for blocked requests.
Analytics & Log Management
You can review matched security rules in the Security Events section. A broader overview of all requests and trends can be found in the Security Analytics section.
For an account-level overview, review the Account Analytics.
Note: Cloudflare Dashboard analytics can likely be sampled.
Note: Exclude the
/cdn-cgi/endpoint from your Security Rules, specifically relevant for challenges.
It is strongly recommended to use Logpush, pushing your logs to storage services (such as R2, S3, or others), SIEMs, or log management providers.
It is highly recommended to set up Notifications to keep up to date with everything, subscribing to incident notifications and periodically review the Cloudflare Status page.
Scans and Penetration Testing Policy
Cloudflare customers may conduct scans and penetration tests (with certain restrictions) on application and network-layer aspects of their own assets.
Two results that regularly show up in reports and are expected behavior rather than findings:
- Non-standard ports reported as open on the resolved IPs. Those are shared Cloudflare anycast IPs serving many customers, not open ports on your origin.
- Warnings on
/cdn-cgi/paths, which are managed by Cloudflare and should be omitted from scans.
You can review all details in the developer documentation.
Automation & User Management
Effective automation and user management are critical for maintaining security, operational efficiency, and governance across your Cloudflare infrastructure.

Infrastructure as Code (IaC) Options
Automate deployments, configuration changes, and rollbacks using these tools:
- Cloudflare API
- SDKs
- Terraform
- For external scripts / uncovered resources, use external.
- If you’re planning to change from Dashboard UI to Terraform, use cf-terraforming.
- Pulumi
Note the API rate limits.
User Access Management
Implement least-privilege access control following these best practices:
Role-Based Access Control (RBAC)
Cloudflare provides predefined roles with specific permission sets:
- Super Administrator - Full account access (limit to 2-3 users)
- Administrator - Most administrative functions except billing and membership
- Domain-specific roles - Scoped to individual zones:
- DNS Administrator
- Firewall Administrator
- Cache Administrator
- Analytics Administrator
Important: API permissions differ from Dashboard permissions. Review API token permissions separately.
User Groups
User Groups enable scalable permission management:
- Create groups based on teams or functions (e.g., “DevOps Team”, “Security Team”)
- Assign multiple IAM policies to each group
- Add users to groups instead of managing individual permissions
- Automatic permission inheritance for group members
Authentication Security
Multi-Factor Authentication (MFA)
- Enforce MFA for all users
- Support for TOTP apps
- Support for passkeys / security keys
- Backup codes for recovery scenarios
Single Sign-On (SSO)
- Configure SSO with SAML or OIDC providers
- Automatic user (de)provisioning with SCIM
API Token Management
Use Account-Owned Tokens for processes or services:
- Create service accounts for CI/CD pipelines
- Implement token rotation policies (i.e. 90-day maximum)
- Scope tokens to minimum required permissions
- Use separate tokens for different environments
- Store tokens in secure vaults
Monitoring and Compliance
Audit Logging
Monitor Audit Logs for:
- User login events and MFA usage
- Permission changes and role assignments
- API token creation / deletion
- Configuration modifications
- Failed authentication attempts
Export audit logs via:
Access Reviews
Establish regular review cycles:
- Quarterly: Review Super Administrator and Administrator assignments
- Monthly: Audit API tokens and remove unused ones
- Weekly: Check audit logs for anomalous activity
- Automated: Alert on privilege escalations or new user additions
Compliance Considerations
- Document role assignments for SOC 2, ISO 27001 compliance
- Implement separation of duties
- Maintain access control matrices
- Regular attestation of user access rights
Best Practices Summary
- Principle of Least Privilege: Start with minimal permissions and add as needed
- Use Groups: Manage permissions via groups, not individual users
- Automate Everything: Use IaC for reproducible configurations
- Token Hygiene: Rotate API tokens regularly, use scoped permissions
- Monitor Continuously: Set up alerts for suspicious activities
- Document Policies: Maintain runbooks for onboarding/offboarding
- Regular Audits: Schedule periodic access reviews
- Emergency Access: Define break-glass procedures for incidents
For advanced scenarios, consider implementing:
- Build your own custom RBAC using Cloudflare Workers as an authentication and authorization gateway-layer for fine-grained access control
- Integration with identity governance platforms
- Automated compliance reporting using the GraphQL Analytics API
Note: these are non-exhaustive resources and a generalization of proper user and account management practices. Follow industry-standards and implement appropriate procedures within your organization.
Origin Server Protection
Generally, it’s recommended to properly secure and manage your origin servers.
When migrating to Cloudflare, it’s highly recommended to rotate Origin Server IPs and proxy all DNS records.
There’s a variety of different ways and options explained on the Developer Documentation to protect your origin server, as well as prepare for surges or spikes in web traffic for seasonal events, such as during holidays or product launches.
Note: Review the Post-Quantum Cryptography (PQC) documentation.

Additionally, review and enable the available Managed Transforms options to add some bot protection headers, remove “X-Powered-By” headers, or even create your own Content Security Policy (CSP) with the Transform Rules.
Reference: Encryption modes.
HTTP/S Use Cases
Fighting Automated Requests (Bots)
A general goal is protecting against automated requests and bots – though there are different types of bot attacks and often it’s about fraud detection or solving one of these use cases:
- Credential / Credit Card Stuffing
- Content Scraping
- Inventory Hoarding
- Account Takeover (ATO)
- Fake Account Creation
- Content Spam
The best approach to combating bots depends on the Cloudflare features available and configured, as well as the specific types of bot attacks being observed. DDoS attacks are usually also launched by botnets. Every website is unique, and often so are the attack patterns it faces. In general, fighting bots is a cat-and-mouse game, requiring continuous adaptation to evolving threats. Cloudflare continuously enhances its capabilities based on customer feedback and its Threat Intelligence to try to stay ahead.
Wanted vs. Unwanted Automation
The goal is not to “block all bots”. The goal is to allow useful automation, constrain ambiguous automation, and stop abusive automation. Cloudflare’s own framing is that the important distinction is often what the traffic is doing, not simply whether it is a bot or a human: see Moving past bots vs. humans.
Cloudflare Verified Bots are automated services Cloudflare has identified as generally useful or expected, such as search-engine crawlers and monitoring services. Verified does not automatically mean “desired everywhere”. For example, a search crawler may be allowed on public content but should usually not be allowed to crawl login, checkout, account, admin, or API mutation endpoints unless there is a specific business reason.
| Traffic class | Examples | Default posture | Cloudflare controls |
|---|---|---|---|
| Wanted verified bots | Googlebot, Bingbot, social previews, approved monitoring | Skip only where the business wants this traffic | Verified Bots, WAF Skip rules for narrow paths, customer-managed allowlists for owned systems |
| Declared AI/search/content crawlers | Known AI/search crawlers and content consumers | Allow, block, or constrain based on content/business policy | Detection IDs, AI Crawl Control, Bot Preference Sync, BotBase for Operators, robots.txt |
| User-directed agents | Browser or assistant traffic acting on behalf of a real user | Prefer risk-based controls; avoid blanket blocking when behavior is legitimate | Bot Management variables, Turnstile, Clearance / pre-clearance, application-layer step-up |
| Unknown automation | curl, Python requests, commodity headless browsers, suspicious TLS/browser fingerprints | Baseline → challenge/rate-limit → block if abusive | Bot Score, JavaScript Detections, JA3/JA4 fields, WAF Custom Rules, Rate Limiting Rules |
| Malicious fraud bots | Credential stuffing, carding, fake signups, scraper farms, inventory abuse | Block, rate-limit, challenge, or route to origin fraud workflow | Account takeover Detection IDs, Leaked Credentials Detection, Turnstile Ephemeral IDs, API Shield |
Important distinctions:
- Verified bot means Cloudflare recognizes the bot category/operator. It does not mean every request from that bot is business-approved for every endpoint.
- Low Bot Score is a risk signal, not a complete fraud verdict. Stronger actions should combine Bot Score with endpoint sensitivity, method, velocity, Detection IDs, JA3/JA4, leaked credentials, session/user context, and business impact.
- User-Agent is not identity. It is easy to spoof. Prefer Cloudflare-provided bot signals, request behavior, cryptographic or verified signals where available, and application context.
Layered Mitigation Approach
To effectively mitigate bot traffic, consider the following (non-exhaustive) layered-security approach:
- Allow (skip) Verified Bots or Verified Bot Categories.
- Allow (skip) your
sitemap.xml,robots.txtand RSS feed (if applicable) to everyone. - Block or mitigate unwanted bots (i.e. AI bots) by leveraging Bot Management fields in combination with other security controls, solutions (i.e. Snippets) and fields.
- Example honeypot for bots.
- Enable JavaScript Detections (JSD) and enforce them if possible.
- If enforcement isn’t feasible (i.e. for native mobile apps), consider implementing Turnstile (in WebView for mobile) alongside the WAF or Cloudflare’s new mobile SDK (Enterprise feature), which can be combined with API Shield JWT Validation at the edge or programmatically with Snippets.
- Analyze heuristics using Security Analytics and available fields to build WAF Custom Rules based on your needs and signals.
- Deploy the WAF Managed Rules regularly updated security rules.
- For important endpoints, we also recommend WAF Attack Score enforcement.
- Identify ASN patterns and block unwanted traffic from certain networks or cloud providers (i.e. AWS or GCP)l if no legitimate traffic is expected from them.
- Use Managed IP Lists for dynamic mitigations.
- Use (Body) Payload Inspection to perform more detailed mitigations.
- Apply Rate Limiting based on IP and other characteristics to prevent abuse and credential stuffing attacks.
- This is often combined with Leaked Credentials Detection.
- For APIs, implement a positive security model with API Shield, including Schema Validation and Sequence Mitigation.
- Alternatively, one can use Sequence Rules (or also called Cookie-based Sequences) to track and enforce the order of requests a user has made and the time between requests.
- Caching anything possible (non-user-specific content) can also help reduce the load and resources of the origin servers.
- Cloudflare is gradually rolling out Fraud Detection features, such as disposable email checks.
- Additional bot-related configurations can be adjusted by Cloudflare’s Bot Team on a case-by-case basis when talking to the Support Team.
Some additional interesting methods include:
- Delay action
- Send suspect bots to a honeypot
- price scraping
- Turnstile with Workers
- Data loss prevention
- Forward specific HTTP Request Headers with Managed Transforms Rules for the origin to act on.
Non-HTTP/S Use Cases
There are scenarios where users might want to leverage Cloudflare’s global network and robust L3/L4 DDoS protection without handling TLS termination or processing HTTP/S traffic and payloads. For these specialized use cases, Cloudflare offers several options tailored to non-HTTP/S requirements.
Available Options:
-
Grey-Clouded DNS Records
This involves setting a DNS record to “DNS Only” mode. However, this approach is not recommended, as it exposes the origin server’s IP address, compromising security. -
Spectrum
A powerful TCP/UDP proxy solution that supports various non-HTTP/S protocols.- It is typically recommended to enable Proxy Protocol.
- To avoid unintended handling of TLS, ensure the Edge TLS Termination option is disabled.
-
Privacy Gateway
Privacy Gateway uses the Oblivious HTTP (OHTTP) standard to hide client IPs during backend interactions. Acting as a trusted relay, it forwards encrypted messages between clients and servers without accessing their content, ensuring enhanced privacy and anonymity. -
Magic Transit
Operating at the network layer, Magic Transit offers advanced DDoS protection and traffic management without TLS termination.- For a deeper dive, check out the Magic Transit Reference Architecture.
Additional Resources
For more guidance on avoiding Cloudflare TLS termination and decryption, visit the Cloudflare Data Localization FAQ.
Performance Matters Too!
For application performance recommendations, see: General Application Performance Recommendations.
Disclaimer
Educational purposes only.
This blog post is independently created and is not affiliated with, endorsed by, or necessarily representative of the views or opinions of any organizations or services mentioned herein.
The images used in this article primarily consist of screenshots from the Cloudflare Dashboard or other publicly available materials, such as Cloudflare webinar slides.
The guidelines provided in this post are intended for general educational purposes. They should be customized to fit your specific use cases and traffic patterns. You are responsible for configuring settings according to your unique requirements, and it is important to understand their potential impact. Familiarity with Cloudflare concepts such as WAF Phases, Proxy Status, and other relevant features is recommended.
The author of this post is not responsible for any misconfigurations, errors, or unintended consequences that may arise from implementing the guidelines or recommendations discussed herein. You assume full responsibility for any actions taken based on this content and for ensuring that configurations are appropriate for your specific environment.
For additional learning resources, explore the following:
- Learning Paths
- Enterprise Customer Portal (for Enterprise customers)
- Security Center
For tailored support, and in general, if you have any questions or need assistance, please contact Cloudflare support, or (also for non-customers) call the Under Attack (UA) Hotline in emergency situations.