Security

How to Protect Your Web Server from Layer 7 DDoS Attacks with Cloudflare & UFW

How to Protect Web Server from Layer 7 DDoS Attacks (Cloudflare & UFW Guide) - CpanelFree Guide
Written by Blog

Quick Answer: To protect a Linux web server from Layer 7 application-layer DDoS attacks (HTTP floods), route DNS traffic through Cloudflare Proxy (Orange Cloud) and lock down your server’s UFW firewall so that port 80 and 443 only accept connections from Cloudflare’s published IP ranges, preventing attackers from bypassing the CDN proxy.

Understanding Layer 7 vs Layer 4 DDoS Attacks

While Layer 4 volumetric attacks (SYN floods, UDP amplification) attempt to saturate network bandwidth, Layer 7 Application Attacks mimic legitimate user requests (such as heavy search queries or database POST requests). These attacks consume 100% of PHP-FPM workers and MySQL CPU buffers, crashing the web server with minimal attacker bandwidth.

Step 1: Enabling Cloudflare Proxy and WAF Protection

  1. In your Cloudflare dashboard, ensure all root and sub-records have the Proxy status set to Proxied (Orange Cloud).
  2. Navigate to Security > WAF > Rate Limiting Rules and create a rule restricting any single IP to a maximum of 50 requests per 10 seconds.
  3. During an active attack, toggle Under Attack Mode to enforce a managed JavaScript/Turnstile verification challenge.

Step 2: Locking Down Origin IP in UFW (Prevent Direct Bypass)

If an attacker discovers your direct origin server IP address, they can send traffic directly to your VPS, bypassing Cloudflare completely. To eliminate this vector, configure UFW to allow port 80/443 traffic only from Cloudflare reverse proxy IPs:

#!/bin/bash
# Sync Cloudflare IP ranges with UFW
for ip in $(curl -s https://www.cloudflare.com/ips-v4); do
    sudo ufw allow from $ip to any port 80,443 proto tcp
done

# Deny all other direct incoming web connections
sudo ufw deny 80/tcp
sudo ufw deny 443/tcp
sudo ufw reload

Step 3: Restoring Real Visitor IPs in Nginx / Apache

Because all incoming traffic now arrives from Cloudflare proxy IPs, configure your web server to read the CF-Connecting-IP HTTP header so access logs and Fail2ban see true client IPs:

# /etc/nginx/conf.d/cloudflare.conf
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 104.16.0.0/13;
real_ip_header CF-Connecting-IP;

Local Web Server Rate Limiting with Nginx & OpenLiteSpeed

Even with Cloudflare proxy active, configure local web server rate limiting to prevent memory exhaustion if attackers target un-cached search queries or API endpoints:

# /etc/nginx/nginx.conf
# Define shared memory zone for rate limiting (10 MB stores 160,000 IPs)
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;

# Apply rate limiting to virtual host
location / {
    limit_req zone=one burst=20 nodelay;
    limit_conn addr 10;
    try_files $uri $uri/ /index.php?$args;
}

Automated Origin IP Blackhole via Fail2ban Cloudflare API

You can configure Fail2ban to communicate directly with Cloudflare’s REST API. When Fail2ban detects malicious Layer 7 floods locally, it dispatches an API request to Cloudflare to block the offending IP globally across all Cloudflare edge data centers.

Layer 7 DDoS Mitigation: Nginx FastCGI Microcaching vs Dynamic Floods

When Layer 7 attackers flood dynamic WordPress PHP endpoints (like /?s=random_query), PHP-FPM processes and MySQL CPU usage immediately spike to 100%. Implementing Nginx FastCGI Microcaching caches dynamic HTML pages for 1 to 5 seconds, allowing your server to absorb tens of thousands of requests per second directly from memory without invoking PHP or MySQL:

# /etc/nginx/conf.d/microcache.conf
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=MICROCACHE:10m max_size=500m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

server {
    set $skip_cache 0;
    if ($request_method = POST) { set $skip_cache 1; }
    if ($query_string != "") { set $skip_cache 0; } # Cache search floods!

    location ~ \.php$ {
        fastcgi_cache MICROCACHE;
        fastcgi_cache_valid 200 301 302 2s; # Cache for 2 seconds
        fastcgi_cache_use_stale error timeout updating invalid_header http_500;
        fastcgi_no_cache $skip_cache;
        fastcgi_cache_bypass $skip_cache;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
    }
}

Testing DDoS Resilience with Simulated Load Tools

Benchmark your server’s rate limiting and caching resilience using HTTP load-testing utilities like wrk or vegeta from an external test instance to verify that un-cached floods are successfully dropped before consuming server memory.

Mitigating Slowloris & Slow HTTP Post Attacks on Nginx

Slowloris attacks keep thousands of HTTP connections open simultaneously by sending headers extremely slowly, exhausting the web server’s connection pool without triggering standard volumetric packet thresholds. Harden Nginx timeout directives to drop slow connection attempts aggressively:

# /etc/nginx/conf.d/anti_slowloris.conf
# Aggressive timeouts to terminate slow-drip attacker sockets
client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 15s;
send_timeout 10s;
reset_timedout_connection on;

Automated Origin IP Blackhole Synchronization via Cron

Cloudflare periodically updates its global reverse proxy IP ranges. Create an automated monthly cron script to ensure your UFW firewall rules remain synchronized with Cloudflare’s published CIDR blocks:

# /etc/cron.monthly/update-cloudflare-ufw.sh
#!/bin/bash
curl -s https://www.cloudflare.com/ips-v4 -o /tmp/cf_ips.txt
for ip in $(cat /tmp/cf_ips.txt); do
    sudo ufw allow from $ip to any port 80,443 proto tcp
done
sudo ufw reload

Built-in Anti-DDoS Protection on CpanelFree

Want instant DDoS resilience without complex iptables scripts? CpanelFree provides multi-terabit edge mitigation, real-time WAF filtering, and free cPanel hosting at $0 forever.

Launch Free Website

Frequently Asked Questions

How can an attacker find my hidden origin server IP?

Common origin leaks include historical DNS records (SecurityTrails), outbound email headers (SMTP sending from origin IP), or non-proxied subdomains (e.g. mail.yourdomain.com or cpanel.yourdomain.com).

About the author

Blog

DevOps architect and Linux sysadmin specializing in server hardening, OpenLiteSpeed performance optimization, and free cloud hosting infrastructure.

Leave a Comment