How to block a country to access your site behind Cloudflare

Sylvain Witmeyer
2 min readOct 3, 2019

Recently a client has an increasing number of fake transactions at his shop.

The buyer was using paypal pro to buy cheap items. He was ordering several times a day, checked out as guest to avoide the creation of an account and every time the transaction was canceled for the reason : card stolen.

He had different IPs for each order, so even after blocking a few of them, this was not enough to discourage him. The only pattern was, all the IPs started with 41.10X.XX.XX. Locating them tells us that the buyer was in Algeria.

Because my client works mainly in North America and according to Google Analytics he has almost no traffic from Algeria, he decided to restrict access to his shop for the whole country.

There are different ways of banning IPs, but we are using Cloudflare (like almost all my clients) which means that the IP the server sees is an IP from Cloudflare not the visitor's.

But we can rely on 2 headers that Cloudflare append to the request.

  • X-Forwarded-For which contains the IP of the visitor
  • CF-IPCountry which contains the two character country code of the originating visitor’s country.

The latter one is cool because it avoids the resolution IP<->Country to be done by the server. Thanks to this custom header, we can use it to block access to the website. This server is using apache so we can add the following rules in a .htaccess

<IfModule mod_setenvif.c>
SetEnvIf CF-IPCountry DZ Block=1
SetEnvIf CF-IPCountry CI Block=1
Order allow,deny
Allow from all
Deny from env=Block
</IfModule>

We set an Environment variable Block=1 if the header CF-IPCountry is DZ or CI. Then we deny access if the variable Block is present.

Conclusion

Short and sweet. I'm still wondering why paypal doesn't detect any of these transactions as a fraud.

If you are facing the same problem, another solution could be to restrict the country in paypal config which would probably be better, or also in the shop itself but this adds a little overhead.

--

--