How to detect a visitor's country of origin with Cloudflare

4828932145 c8460f05bc o
Credit: Steve Snodgrass via Flickr

Who goes there?


There are a bunch of reasons why you'd want to know what country a visitor is coming from on your website or application. Two common ones are security hardening (e.g. block an entire country from hitting your site) and country specific redirects (e.g. send UK visitors to your UK site).

The typical way to detect a country of origin is to compare the IP address of the visitor against a geo-ip database to determine the country. To keep your site performing well, you usually have a local data file containing the IP ranges of each country and compare against that file. The downsides to this technique are obvious - computational overhead for each visitor and keeping your database up to date. If you're just banning a range of IP addresses this comparison can be handled with IPTables rather than your actual application, but you might not always have access to IPTables on your server and you might want to do more than just block the request.

To make this country of origin determination simple you can leverage Cloudflare. If you have IP Geolocation enabled (on by default), Cloudflare will pass a header along with every request that you can read from to get the ISO Country Code of the visitor. 

ipgeolocation1 Cloudflare
ipgeolocation2 Cloudflare

To retrieve the country code, just check the header named HTTP_CF_IPCOUNTRY and you'll have the value.

For example in PHP:

$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"]; //from cloudflare headers

You can then easily perform some logic based on country of origin. Much easier.

Of course, just like all IP based logic this is easily beaten using a proxy or IP spoofing. For the vast majority of real users however, this will work just fine. 

ITWorld DealPost: The best in tech deals and discounts.