Jakub Muda
Jakub Muda

Reputation: 6744

Auto redirect to website version based on user country

I am trying to create auto redirect for my website based on a country of a user. The website will be available only in 1 language but pricing will be based on a country currency. It's a simple website with main page, terms and conditions, privacy policy and that's all. My hosting provider is OVH and I suppose they have Apache servers.

Here is what I am trying to do:

  1. Main adress http://www.example.com
  2. User in Poland with Polish language uses http://www.example.com . I also own a country domain http://www.example.pl
  3. User in Canada with Polish language is auto redirected to http://www.example.com/ca
  4. User in US with Polish language is auto redirected to http://www.example.com/us
  5. All Polish users from countries other than Canada and US use http://www.example.com
  6. OPTIONAL Users from Poland CAN'T acces version for canadian users, and vice versa
  7. All users speaking English or any other language, in any country, access http://www.example.com. In the header I have links allowing to change language versions freely and go to http://www.someadress.com and vice versa.

EXAMPLE

SAMPLE CODE

I was trying to do it with php but it didn't work as intended. Servers are located in France and I was redirected to http://www.test.com

PHP:

$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];
if ($country_code=="PL") {$link = 'http://www.example.com';}
elseif ($country_code=="CA") {$link = 'http://www.example.com/ca';}
elseif ($country_code=="US") {$link = 'http://www.example.com/us';}
else {$link = 'http://www.test.com';}
header("location:$link");
exit;

I tried editing htaccess file but nothing happened:

RewriteEngine On

RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^PL$
RewriteRule ^(.*)$ http://www.example.com [L]

RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^CA$
RewriteRule ^(.*)$ http://www.example.com/ca [L]

RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^US$
RewriteRule ^(.*)$ http://www.example.com/us [L]

Any ideas how can I do it in the easiest possible way?

Upvotes: 0

Views: 1427

Answers (1)

ThomasV
ThomasV

Reputation: 336

Check that you have the mod_geoip module (GeoIP Extension) installed on your server.

Then, tweak your .htaccess file accordingly :

GeoIPEnable On
GeoIPDBFile /path/to/GeoIP.dat

# Start Redirecting countries

# Canada
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CA$
RewriteRule ^(.*)$ http://ca.abcd.com$1 [L]

# India
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^IN$
RewriteRule ^(.*)$ http://in.abcd.com$1 [L]

# etc etc etc...

Documentation: URL

Upvotes: 1

Related Questions