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


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?


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.


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


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


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


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).


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


How can I write simple CF Workers?


Consider that Workes cost 0.5$/1M queries, with a minimum of 5$/month per domain,

Here is a working code sample.

addEventListener('fetch', event => {

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)

closed #10

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