Configuring Cloudflare IP Geolocation

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.

  • The CF-IPCountry header is not visible to visitors in the site's HTTP response
  • XX is used for clients without country code data
  • T1 is used for clients using the Tor network

Configuring IP Geolocation

This feature can be enabled or disabled in the Cloudflare Dashboard through the Network app.

ip_geolocation.png


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

The above configuration examples will only capture the CF-IPCountry information. Alternatively, server administrators often append the log variable cf-ipcountry to their existing log configuration with other Cloudflare headers like cf-ray, cf-connecting-ip, and cf-visitor.

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"};

Related resources

Not finding what you need?

95% of questions can be answered using the search tool. This is the quickest way to get a response.

Powered by Zendesk