Is your website loading slowly? Or did your server suddenly crash due to a suspicious traffic spike? These issues are frequently experienced by website owners, from bloggers to enterprise-scale operations. Without a protective layer, even a simple DDoS (Distributed Denial-of-Service) attack can be enough to take your website offline within minutes.
Cloudflare serves as a solution to enhance web performance while maintaining security. Technically, Cloudflare operates as a reverse proxy that bridges visitors (clients) with your main server (origin server). Every incoming request is filtered first: only safe requests are forwarded to the origin, while malicious threats are blocked immediately before they ever reach your server.
This guide is structured step-by-step based on hands-on testing across various projects, from shared hosting to VPS. Each stage also includes testing methods so you can verify for yourself that the configuration is working correctly.
Prerequisites before getting started:
Ensure you have prepared the following:
- Active Domain: You have a registered domain name (e.g., example.com).
- IP Address: You know the IP address of your server or hosting.
- Registrar Access: You have login access to your domain management panel (Registrar).
Important Note:
This guide is structured sequentially. DNS must be active before enabling SSL, and SSL must be functioning normally before you configure the WAF, and so on. Follow each step in order to avoid configuration conflicts (errors).
1. Understanding DNS (Domain Name System)
Before diving into how Cloudflare works, it's helpful to first understand DNS (Domain Name System). Think of DNS as the internet's phonebook; this system translates the domain names we typically type (like example.com) into numerical IP addresses (like 203.0.113.10) so computers can process them.
The analogy is simple: if an IP address is your home's physical address, then a domain name is the location name you type into a digital map application. DNS acts as the map itself, directing you to the correct address.
Essential DNS Components to Understand
A Record: Connects a domain name to an IPv4 address.
example.com. 3600 IN A 203.0.113.10AAAA Record: Connects a domain name to an IPv6 address.
example.com. 3600 IN AAAA 2001:db8::1CNAME Record (Alias): Redirects one subdomain to another domain or hostname.
www.example.com. 3600 IN CNAME example.com.MX Record: Specifies the mail server for the domain's email services.
example.com. 3600 IN MX 10 mail.example.com.TXT Record: Stores text data for verification purposes such as SPF, DKIM, and others.
example.com. 3600 IN TXT "v=spf1 include:_spf.google.com ~all"NS Record (Nameserver): Determines which DNS server has full authoritative control over the domain. This is the part we will later change to Cloudflare's nameservers.
example.com. 86400 IN NS ada.ns.cloudflare.com.
example.com. 86400 IN NS bob.ns.cloudflare.com.Once you switch your nameservers to Cloudflare, Cloudflare automatically becomes the authoritative DNS provider for your domain. This means Cloudflare will answer every DNS query from across the internet. This is where Cloudflare's core strength lies in managing and securing your domain.
TTL (Time to Live)
TTL is the duration (in seconds) that a DNS record is stored in a resolver's cache.
- Low TTL (e.g., 300 seconds / 5 minutes): DNS changes propagate faster across the network, but query load increases.
- High TTL (e.g., 86400 / 24 hours): Query load decreases, but DNS changes take longer to synchronize (propagate).
Cloudflare automatically manages TTL for every record with a Proxied status. For Non-proxy records (DNS Only), the minimum allowed TTL value on Cloudflare's Free Plan is 60 seconds.
2. Why is Cloudflare Important?
High-Level Security: DDoS and Bot Protection
DDoS attacks occur when millions of infected devices (botnets) flood a single target with traffic simultaneously. A server that typically handles hundreds of requests per second can collapse within minutes under such an attack.
Cloudflare leverages its global Anycast network to address this. When an attack occurs, malicious traffic is absorbed and distributed across hundreds of Cloudflare data centers worldwide, rather than directly hitting your server. With its massive network capacity, Cloudflare ensures your origin server continues running normally even under attack. Additionally, Cloudflare's real-time analysis system can distinguish genuine human visitors from harmful bots or crawlers.
Performance & CDN: Global Server Network
A CDN (Content Delivery Network) is a network of servers distributed across various regions worldwide. As of 2026, Cloudflare operates more than 330 data centers. If your server is located in Europe and your visitor is in Jakarta, Cloudflare will serve content that has been cached from the nearest data center (e.g., Singapore). The result is drastically reduced latency and faster website loading. Anycast technology ensures every request is automatically routed to the most efficient path.
Resource Efficiency: Automatic Caching
The caching feature allows most visitor requests to be handled directly by Cloudflare without burdening your origin server. This significantly conserves CPU and bandwidth usage on your server. This efficiency can even reduce server workload by 60–70% for high-traffic websites.
Free SSL/TLS
Cloudflare provides free SSL/TLS certificates for all its users. Beyond securing data, HTTPS usage is now a crucial factor in Google Search ranking evaluations.
| Aspect | Standard DNS (ISP/Registrar) | Cloudflare DNS |
|---|---|---|
| Resolution speed | Slow to moderate | Very fast (Global Anycast) |
| DDoS protection | None / Limited | Unmetered DDoS mitigation |
| CDN | None | 330+ global locations |
| SSL/TLS | Manual/Paid | Free and automatic |
| WAF | None | Available (OWASP ruleset) |
| Traffic analytics | None | Real-time dashboard |
| Origin IP masking | No | Yes (Server IP not publicly exposed) |
| Base pricing | Free (included with hosting) | Free (Free Plan) |
3. When Might You Not Need Cloudflare?
Transparency is part of building trust. Here are situations where Cloudflare might not be the best solution:
- Internal/intranet websites: Websites accessible only from an internal network don't need to route through Cloudflare. You can use VPN solutions or Cloudflare Zero Trust instead.
- Applications with extremely latency-sensitive requirements: Real-time trading, gaming streaming, or applications requiring sub-1ms latency might be impacted by the additional hop through Cloudflare.
- Websites requiring a static origin IP address: Some third-party services require direct connection to the server's IP address. Use Cloudflare Spectrum or ensure that endpoint is bypassed.
- Strict local data compliance: Using Cloudflare requires configuring Regional Services (available on paid plans) if regulations mandate that data must not leave a specific territory.
- Single vendor dependency: Cloudflare becomes a SPOF (Single Point of Failure) if there's no backup. Your website would become inaccessible if Cloudflare experiences an outage.
4. Cloudflare Configuration Guide
Step 1. Creating a Cloudflare Account
- Go to dash.cloudflare.com/sign-up.
- Enter your email address and password.
- Verify your email via the confirmation link sent by Cloudflare.
- Log in to the Cloudflare dashboard.
Cloudflare does not require a credit card for the Free plan. There is no limit to the number of domains you can add to a Free account.
Step 2. Adding Your Domain to Cloudflare
- Click the
Add → Connect a domainbutton on the Cloudflare dashboard. - Enter your domain name (e.g., example.com).
- Click
Continue. - Cloudflare will run an automatic DNS scan to import all discovered DNS records. Review the results to ensure the following data is correct:
- A Record → Your server's IP address.
- CNAME Record (if applicable).
- MX Record (if using email hosting services).
- If any records are missing, add them manually before proceeding to the next stage.
- Click
Continue. - Select your desired service plan. The Free plan is an excellent choice for beginners as it already includes:
- Global CDN
- Unmetered DDoS Mitigation
- Free Shared SSL Certificate
- Basic Web Application Firewall (WAF)
- Click
Continue.
Cloudflare will display two new nameservers you must use, for example:
ada.ns.cloudflare.com
bob.ns.cloudflare.comThese nameserver values are unique per domain. Note the nameservers displayed in your dashboard.
The domain status in your dashboard will change to Pending Nameserver Update after the domain is successfully added. This condition is entirely normal; please proceed to Step 3.
Step 3. Changing Nameservers at Your Domain Panel (Registrar)
This step is performed through your domain management panel at the place where you purchased your domain (Registrar), not in the Cloudflare dashboard. Although each Registrar's interface may differ, the workflow remains similar.
Example general steps:
- Log in to your Client Area or domain control panel.
- Navigate to Domain → Domain List.
- Click on the domain name you want to configure.
- Select the
NameserverorDNS Managementmenu. - Replace the old nameservers with the two Cloudflare nameserver addresses you noted from Step 2.
- Save the changes.
DNS propagation can take up to 24–48 hours to spread across all internet resolvers, although it often completes within hours. During this propagation period, some visitors may still connect via the old DNS.
Testing Step 3
Use the dig or nslookup command to check your domain's nameservers:
dig NS example.com +shortExpected output:
ada.ns.cloudflare.com.
bob.ns.cloudflare.com.Second verification: ensure the IP address that appears belongs to Cloudflare:
ping example.comThe IP address that appears should no longer be your server's original IP address, but rather one from Cloudflare's IP range (cloudflare.com/ips).
Verify with curl; check for the CF-RAY header as proof that traffic is passing through Cloudflare's network:
curl -I https://example.comIf you find the CF-RAY header and Server: cloudflare in the response, it means your DNS configuration was successful. The domain status in the Cloudflare dashboard will change from Pending to Active (indicated by a green checkmark icon).
Step 4. Enabling SSL/TLS (HTTPS)
SSL/TLS certificates will be available automatically once your domain is active on Cloudflare. However, you still need to select the encryption mode that best suits your origin server's configuration. Open the Cloudflare dashboard, select your domain, then go to SSL/TLS → Overview.
Four SSL/TLS mode options are available for you to use:
| SSL/TLS Mode | Encryption Client → Cloudflare | Encryption Cloudflare → Origin | Use Case Condition |
|---|---|---|---|
| Off | None | None | Highly not recommended (HTTP only) |
| Flexible | Yes (HTTPS) | No (HTTP) | Shared hosting without SSL on the origin |
| Full | Yes (HTTPS) | Yes (Can use self-signed) | Server already has SSL, even if not CA-validated |
| Full (Strict) | Yes (HTTPS) | Yes (Valid/CA-signed certificate required) | VPS/Server with Let's Encrypt or Cloudflare Origin CA |
Recommendation: Use Full (Strict) mode if you have full control over your server and have installed an SSL certificate (such as Let's Encrypt). For shared hosting users whose provider already supplies SSL, use Full mode. Avoid Flexible mode for websites handling sensitive data, as the connection between Cloudflare and your server remains unencrypted.
Enabling Always Use HTTPS
Ensure all HTTP traffic is automatically redirected to HTTPS. Go to SSL/TLS → Edge Certificates, then enable the Always Use HTTPS option.
Enabling HSTS (Optional, Advanced)
HTTP Strict Transport Security (HSTS) instructs browsers to always use HTTPS for your domain, even before the first request is made. Enable this feature with caution; if you disable HTTPS later, your website could become completely inaccessible to visitors.
# HSTS header sent by Cloudflare after the feature is enabled:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preloadA max-age value of 31536000 means browsers will remember to always use HTTPS for the next year. The includeSubDomains parameter ensures this protection also applies to all your subdomains, while preload allows your domain to be listed in the global HSTS Preload list managed by Google.
Testing Step 4
# Check SSL certificate
curl -vI https://example.com 2>&1 | grep -E "SSL|TLS|issuer|expire"
# Or use openssl
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -issuer -datesThe output should show an Issuer from Cloudflare or Let's Encrypt, as well as a valid Expiration Date. Ensure your browser displays a padlock icon in the address bar as a sign that the connection is secure.
# Test HTTP to HTTPS redirect
curl -I http://example.comThe response should show a 301 Moved Permanently status with Location: https://example.com.
Step 5. Performance Optimization: Auto Minify and Brotli
5.1 Auto Minify
Auto Minify removes unnecessary characters (such as spaces, comments, and newlines) from HTML, CSS, and JavaScript files before they are sent to visitors. The result is smaller file sizes and much faster data transfer.
Go to Speed → Optimization → Content Optimization, then enable Auto Minify for all three file types.
5.2 Brotli Compression
Brotli is a compression algorithm developed by Google that is 15–25% more efficient than Gzip for web content. Cloudflare supports Brotli natively.
Enable the Brotli option in the same menu (Content Optimization).
5.3 Rocket Loader (Optional)
Rocket Loader prioritizes website content rendering by loading JavaScript asynchronously. This feature is particularly useful if your website feels sluggish due to numerous third-party scripts. However, be sure to test first, as some JavaScript plugins may encounter issues.
Testing Step 5
Use the curl command to verify that Brotli is active by checking the Content-Encoding header:
curl -H "Accept-Encoding: br" -I https://example.comExpected response header:
Content-Encoding: brIf a visitor's browser does not support Brotli, Cloudflare will automatically fall back to Gzip (Content-Encoding: gzip).
Additionally, you can test your website's speed improvement using the following tools:
- PageSpeed Insights: Performance analysis from Google.
- WebPageTest: Testing access from various geographic locations.
- GTmetrix: Detailed web performance reports.
Step 6. Caching Configuration
Caching is one of the features with the most significant impact on website performance. By storing content on Cloudflare's edge servers, subsequent requests no longer need to be forwarded to the origin server.
Go to Caching → Configuration:
- Caching Level: Select
Standardfor general use. ChooseIgnore Query Stringif you want to ignore URL parameters when determining cache keys. - Browser Cache TTL: Set the duration for cache storage in visitors' browsers. A 4-hour duration is a safe choice for static websites, while for dynamic websites, a lower value is recommended.
Cache Rules (Custom Cache Rules)
Go to Caching → Cache Rules to create more specific rules. Example: You can configure all image files to be cached for 30 days.
# Example Cache Rule logic for static files
# Field: File Extension
# Operator: is in
# Value: jpg, jpeg, png, gif, webp, svg, ico, woff, woff2, css, js
# Action: Cache Everything
# Edge Cache TTL: 1 monthTesting Step 6
# Check cache headers from Cloudflare
curl -I https://example.com/image.jpgExpected response headers:
CF-Cache-Status: HIT # Content served from Cloudflare cache
Age: 3600 # Cached for 1 hour
Cache-Control: public, max-age=86400CF-Cache-Status values can be:
- HIT: served from Cloudflare cache
- MISS: not in cache, fetched from origin
- BYPASS: cache bypassed (usually due to cookies or no-cache headers)
- DYNAMIC: content not cached (dynamic pages)
Step 7. Protecting Your Origin Server from Cloudflare Bypass
Attackers can sometimes discover your server's original IP address through DNS history, email headers, or old logs. This allows them to access your server directly and bypass all of Cloudflare's security systems. This step aims to close that vulnerability.
Ensure your server only accepts connections from Cloudflare's official IP ranges. The easiest way is to use the Authenticated Origin Pulls feature or restrict access via firewall (UFW/iptables) at the server level.
This action ensures all data traffic must pass through Cloudflare's security filters before reaching your server.
7.1 Whitelist Cloudflare IPs on Server Firewall
Configure your server firewall (such as iptables or ufw) to only accept HTTP/HTTPS connections from Cloudflare's official IP ranges. This step is crucial to prevent any external party from accessing your server directly. The complete, up-to-date list of Cloudflare IPs is always available at cloudflare.com/ips.
Using iptables:
Enter the following commands to allow traffic from Cloudflare and block other access to ports 80 and 443:
# Remove default HTTP/HTTPS rule
iptables -D INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT 2>/dev/null
# Allow Cloudflare IPv4 (fetch automatically)
curl -s https://www.cloudflare.com/ips-v4/ | while read ip; do
iptables -I INPUT -p tcp -m multiport --dports 80,443 -s "$ip" -j ACCEPT
done
# Allow Cloudflare IPv6 (fetch automatically)
curl -s https://www.cloudflare.com/ips-v6/ | while read ip; do
ip6tables -I INPUT -p tcp -m multiport --dports 80,443 -s "$ip" -j ACCEPT
done
# Drop everything else
iptables -A INPUT -p tcp -m multiport --dports 80,443 -j DROPUsing UFW:
# Reset old rules for HTTP/HTTPS (optional, be careful if other rules exist)
ufw delete allow 80/tcp 2>/dev/null
ufw delete allow 443/tcp 2>/dev/null
# Allow Cloudflare IPv4
curl -s https://www.cloudflare.com/ips-v4/ | while read ip; do
ufw allow from "$ip" to any port 80 proto tcp
ufw allow from "$ip" to any port 443 proto tcp
done
# Allow Cloudflare IPv6
curl -s https://www.cloudflare.com/ips-v6/ | while read ip; do
ufw allow from "$ip" to any port 80 proto tcp
ufw allow from "$ip" to any port 443 proto tcp
done
# Deny everything except Cloudflare
ufw deny 80/tcp
ufw deny 443/tcp
# Reload UFW
ufw reloadImportant Warning: Ensure that the SSH port (default 22) or other management ports are not accidentally blocked when configuring your firewall. Neglecting this can cause you to be locked out and lose access to your own server. Always verify that rules for the SSH port are active before applying restrictions to ports 80 and 443.
7.2 Cloudflare Authenticated Origin Pull
The Authenticated Origin Pulls feature ensures that only Cloudflare can communicate with your origin server. This system works by requiring Cloudflare to present a valid client TLS certificate every time it establishes a connection. Enable this feature via SSL/TLS → Origin Server → Authenticated Origin Pulls.
Testing Step 7
# Try accessing the server IP directly (not via domain)
# Should be refused or timeout
curl -I http://<YOUR_SERVER_IP>
# Access via domain (through Cloudflare) should still work
curl -I https://example.comSuccessful protection is indicated by a connection refused or timeout message when accessing the server IP directly. Conversely, access via the domain should continue to work normally and return a 200 OK status.
Step 8. Web Application Firewall (WAF)
The WAF (Web Application Firewall) is an application-layer (Layer 7) protection layer responsible for filtering, monitoring, and blocking malicious HTTP requests. This feature filters traffic within Cloudflare's infrastructure before it reaches your origin server.
Go to Security → Security rules. Click the Create rule → Custom rules button to start creating configurations.
Here are some examples of WAF implementations:
Blocking IP Addresses
Block a single IP address, for example 165.245.183.105:
# Rule name: Block single IP
# Field: IP Source Address
# Operator: equals
# Value: 165.245.183.105
# Choose action: Block
# Form builder will generate the expression:
(ip.src eq 165.245.183.105)Block multiple IP addresses:
# Rule name: Block multiple IPs
# Field: IP Source Address
# Operator: is in
# Value: 165.245.183.105 164.245.130.213 164.245.200.105
# Choose action: Block
# Form builder will generate the expression:
(ip.src in {165.245.183.105 164.245.130.213 164.245.200.105})Block IP range (CIDR)
# Rule name: Block IP range
# Field: IP Source Address
# Operator: is in
# Value: 165.245.128.0/17
# Choose action: Block
# Form builder will generate the expression:
(ip.src in {165.245.128.0/17})Blocking ASN (Autonomous System Number)
ASN (Autonomous System Number) is a unique identifier for networks operated by a single entity, such as an ISP, hosting company, or cloud service provider. Blocking an ASN is useful for blocking traffic from hosting providers that are frequent sources of attacks, for example, certain VPS providers often misused for malicious purposes.
How to find the ASN for a specific IP address:
# Using whois and Team Cymru services combination
whois -h v4.whois.cymru.com "-v 165.245.183.105"
# Response:
AS | IP | BGP Prefix | CC | Registry | Allocated | AS Name
14061 | 165.245.183.105 | 165.245.176.0/20 | US | arin | 2025-04-24 | DIGITALOCEAN-ASN - DigitalOcean, LLC, US
# Or use the online tool from bgp.he.net
# URL: https://bgp.he.net/ip/165.245.183.105Custom rule to block AS Number:
# Block a single ASN
# Field: ASN
# Operator: equals
# Value: 14061
# Generated expression: (ip.src.asnum eq 14061)
# Block multiple ASNs at once
# Field: ASN
# Operator: is in
# Value: 14061 134963
# Generated expression: (ip.src.asnum in {14061 134963})Warning: Blocking an entire ASN has significant impact. ASNs from large hosting providers can encompass millions of IP addresses used by legitimate users. Consider using Managed Challenge (CAPTCHA) as the action instead of direct Block so legitimate users can still access your website.
Blocking Access to Specific URLs
Blocking access to specific URLs or paths is very useful for protecting admin pages, configuration files, or endpoints that should not be publicly accessible.
Block access to sensitive files:
# Field: URI Path
# Operator: contains
# Value: .env
# Or
# Field: URI Path
# Operator: contains
# Value: .git
# Generated expression:
(http.request.uri.path contains ".env") or (http.request.uri.path contains ".git")Block WordPress admin URL except for specific IPs:
# Field: URI Path
# Operator: contains
# Value: /wp-admin
# And
# Field: IP Source Address
# Operator: is not in
# Value: 182.11.130.112 182.11.130.11
# Generated expression:
(http.request.uri.path contains "/wp-admin" and not ip.src in {182.11.130.112 182.11.130.110})Blocking Access from Specific Countries
Cloudflare uses IP address geolocation data to determine the country of origin for each request. You can block or present a challenge to visitors from specific countries.
Block specific countries:
# Field: Country
# Operator: is in
# Value: select countries to block
# Generated expression: (ip.src.country in {"XX" "YY"})Allow only specific countries (Whitelist):
# Field: Country
# Operator: is not in
# Value: select countries to allow
# Generated expression: (not ip.src.country in {"XX" "YY"})Important Note: Geoblocking has limitations because VPNs and proxies allow users to bypass these restrictions. Additionally, ensure you do not block search engine bots like Googlebot or Bingbot, which are crucial for SEO. Cloudflare recognizes trusted search engine bots by default and excludes them from most blocking rules.
WAF Testing:
# Accessing the website from a blocked source will receive the following response:
Sorry, you have been blocked
You are unable to access example.comStep 9: Under Attack Mode: Emergency Response During DDoS
Under Attack Mode is an emergency feature that displays a JavaScript challenge page to all visitors before allowing access to your website. Legitimate browsers will automatically complete this challenge within seconds.
This mode is effective for mitigating:
- HTTP DDoS floods
- Bots that cannot execute JavaScript
- Layer 7 application attacks
You can enable it via Domain → Overview. In the right sidebar, Quick Actions → Under Attack Mode.
Important: Avoid enabling Under Attack Mode continuously. This mode slows down initial access for legitimate visitors and can impact user experience. Enable this feature only when your website is actively under attack.
Under Attack Mode Testing:
When Under Attack Mode is active, access the website via a browser.
Visitors will see the page: "Checking your browser before accessing..."
The browser automatically completes the JS challenge within 2 to 5 seconds.5. Monitoring and Maintenance
Website security and performance are not the result of a static configuration, but rather the outcome of consistent monitoring and maintenance. Through the Cloudflare panel, you can monitor traffic graphs, detect attack anomalies in real-time, and ensure every configured rule remains relevant to the latest threat patterns. Conducting routine audits of security events and reviewing analytics will help you optimize infrastructure resources while keeping the user experience smooth.
Analytics & Logs
Go to Domain → Analytics & logs:
- HTTP Traffic: monitors the volume and distribution of requests to your website, including country of origin and key metrics such as requests, bandwidth, and unique visitors.
- Web analytics: helps you understand web page performance as directly experienced by your website visitors.
Security Analytics
Go to Domain → Security → Analytics:
- Traffic: provides comprehensive information about incoming HTTP requests to your domain, including distribution analysis, data source (Cloudflare global network or origin server), and suspicious traffic analysis.
- Events: review of mitigated requests flagged by Cloudflare security features, with options for sampled logs on the Free plan or comprehensive data for paid customers.
Automatic Notifications
Enable notifications under Manage account → Notifications to receive alerts for events such as:
- DDoS attack detected.
- SSL certificate approaching expiration.
- Origin server health check failure.
- Traffic anomaly spike.
Closing
Cloudflare is one of the best infrastructure decisions for your website, especially because enterprise-grade features are available for free on the Free plan. Website security is not a one-time project, but rather an ongoing process. You need to routinely monitor event logs, update firewall rules, and follow Cloudflare's changelog to access the latest features and rulesets. The combination of global CDN speed, robust DDoS protection, and customizable WAF enables Cloudflare to deliver capabilities equivalent to paid enterprise solutions without additional cost for most use cases.




