Disabling Direct Access to Origin Server on Apache

I solved this issue by myself and I’m sharing it for the good of others. It turned out that the problem was that I was using Nginx in front of Apache, and Nginx has a configuration to set the real IP for Cloudflare requests. However, Apache never received Cloudflare IPs at all.

So I decided to use Nginx and block requests on that end. However, the same problem came up there while using allow-deny directives.

The solution is to add a ‘geo’ directive to the Nginx config at the http level and set a flag there. Then, check that flag in the location {} block as follows:

http {
    geo $realip_remote_addr $is_cloudflare_ip {
        default          0;
        103.21.244.0/22  1;
        103.22.200.0/22  1;
        103.31.4.0/22    1;
        104.16.0.0/12    1;
        108.162.192.0/18 1;
        131.0.72.0/22    1;
        141.101.64.0/18  1;
        .... add all IPs here
    }
}

Also, check the $is_cloudflare_ip flag in the location {} block and return a 403 error if it does not match:

if ($is_cloudflare_ip != 1) {
    return 403;
}

I hope this helps anyone else who may be experiencing the same issue.

1 Like