Is there any way to block certain country ips on Cloudflare's free version?


#1

Enterprise version is pricey. If country blocking is on pro plan then i can buy but its on enterprise.
So i need to find a free way to block certain ip range of whole country. How can I do that?


#2

Cloudflare can add a header indicating the country of a request’s origin, you could use this at the webserver level to block requests. With some creativity, you could probably write a Service Worker to do this, although I’ve not personally tried this approach.


#3

Not much creativity actually, it’s pretty easy, a couple of lines.


#4

You can block ASNs. If you manage to resolve them with a script you can block them.


#5

But there is already an header with the country code, why bother with ASNs?


#6

You can download a list of IPs, ASNs and Country Codes to get an idea of what a task it would be to list every ASN from any particular country unless it happens to be a particularly tiny country.

@matteo The goal was to block certain countries from accessing a site via Cloudflare. This is available to Enterprise customers but could be done manually by adding ASNs (unless there is a limit to the number of rules? I’ve never looked). Using the country header is easy if you control the backend hosting server, but harder if you don’t (unless you want to pay for Service Workers).


#7

You can simply write a simple CF Workers, get the CF header for the country and reply accordingly.


#8

How can I write simple CF Workers?


#9

Consider that Workes cost 0.5$/1M queries, with a minimum of 5$/month per domain, https://www.cloudflare.com/products/cloudflare-workers/.

Here is a working code sample.

addEventListener('fetch', event => {
  event.respondWith(blockCountries(event.request))
})

async function blockCountries(request) {
  let countries = ['IT', 'US'] // here you list all the country codes you want to block.

  if (countries.indexOf(request.headers.get('CF-IPCountry')) > -1) {
    return new Response('Sorry, this page is not available.', { // This response can be whatever you want,
      status: 403,
      statusText: 'Forbidden'
    })
  } else {
    return fetch(request)
  }
}

#10

This topic was automatically closed after 14 days. New replies are no longer allowed.