IP Geolocation allows site owners to capture country codes for their visitors on their origin web server. Learn how to configure the IP Geolocation feature to geolocate your site's traffic.
Overview
Cloudflare can include the country code of the visitor's IP (in ISO 3166-1 Alpha 2 format) with each request between Cloudflare and the upstream origin web server. This allows site administrators to capture their visitor's IP location in server logging and/or application logic.
The country code value is passed along in the CF-IPCountry request header to the origin web server.
Cloudflare includes country code information for both IPv4 and IPv6 addresses. Currently, the IPv4 information is more robust, but we expect the IPv6 data to improve rapidly.
Configuring IP Geolocation
This feature can be enabled or disabled in the Cloudflare Dashboard through the Network app.
Capturing Geolocation data in server logs
Visitor traffic geolocation information can be captured in origin server logging. Below are two very common web server implementations and how a site administrator could configure custom logging for the IP Geolocation of their visitors.
Apache
LogFormat %{cf-ipcountry}i cloudflare_custom
More about Apache LogFormat
Nginx
log_format cloudflare_custom '"$http_cf_ipcountry"';
More about Nginx log_format
Capturing Geolocation data in application logic
Web applications can also capture and use the IP Geolocation information in their logic. This is useful to direct visitors based on their country or provide defaults such as language and currency. Below are common language examples of how to capture this header into a variable for later use.
PHP
$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];
Python Flask
country_code = request.headers.get('cf-ipcountry')
Note that you'll need to import python flask request module
NodeJS
const country_code = headers['cf-ipcountry'];
Note that you'll need to require http/https and instantiate the createServer() method
C#.Net
string country_code = HttpContext.Current.Request.Headers.Get("cf-ipcountry");
Perl
$country_code = $ENV{"HTTP_CF_IPCOUNTRY"};