Redirect visitors by country on Cloudflare using htaccess

In certain cases we may need to redirect visitors to a particular website, folder, or specific pages.

So how to achieve that if I am using Cloudflare?

Cloudflare have IP Geolocation feature and once enabled the "CF-IPCountry" header will available to all requests. 1

The .htaccess file

We will use SetEnvIf in our .htaccess file. Below example is how to redirect visitors from Indonesia to specific domain:

RewriteEngine on

# Set the CF-IPCountry header value as "Country" variable
SetEnvIf CF-IPCountry "(.*)$" Country=$1

# Than redirect it if the variable match. "ID" for Indonesia 
RewriteCond %{ENV:Country} ID
RewriteRule ^(.*)$ http://www.example.co.id/$1 [R,L]

You can read Cloudflare two letter country codes here.


Author: danpros

I am known as a web geek, business owner, and part-time blogger.

Comments on “Redirect visitors by country on Cloudflare using htaccess”