Mihai Galan
Mihai Galan

Reputation: 446

How can i block all CloudFlare IPs in PHP

I have a problem with some proxy sites that are using cloudflare and they are cloaking and spamdexing my website.

How can i block all cloudflare ip's in php so these sites that are scraping my website get blocked .. or is there any better solution? My website is also using cloudflare.

Upvotes: 0

Views: 890

Answers (3)

Ankh
Ankh

Reputation: 1

I use a firewall rule to block all Cloudflare ip ranges. Works great, no problems so far.

Upvotes: 0

hanshenrik
hanshenrik

Reputation: 21463

luckily, cloudflare provides a list of their IP ranges here, so just check if the connecting IP is within 1 of those ranges, and exit() if it is.

example implementation using the M6Web/Firewall:

use M6Web\Component\Firewall\Firewall;

if(!((new Firewall())->setDefaultState(true)->addList(file('blacklist.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),'localBad')->setIpAddress($_SERVER['REMOTE_ADDR'])->handle())){
     http_response_code(403);
     exit();
}

with an accompanying daily cronjob:

<?php
$ips = file_get_contents ( 'https://www.cloudflare.com/ips-v4' ) . "\n" . file_get_contents ( 'https://www.cloudflare.com/ips-v6' );
file_put_contents ( '/path/to/blacklist.txt', $ips );
  • note that it would be difficult to implement ipv6 cidr ranges manually, thus you should probably use a 3rd-party libary, like the M6Web firewall. also, it would be much more performant to do it with iptables than at the php level.

  • the cronjob is not really required, you can fetch a fresh list of ips with every pageload, but that would probably be very slow, and, perhaps ironically, you'd might get auto ip-banned from cloudflare.com for spamming, thus i highly suggest you use a daily cronjob.

Upvotes: 1

Xymanek
Xymanek

Reputation: 1389

How can i block all cloudflare ip's

My website is also using cloudflare

You cannot - otherwise you will not be able to use cloudflare yourself.

A better solution would be to have your webserver (eg. apache or nginx) check the host header (which is what the user sees in the address bar) and if it's something other than your normal domain just 301 redirect (permanent) - this will tell search engines that the content has "moved" from scrapping site to legitimate site

Upvotes: 0

Related Questions