Automatically redirect visitors to country specific page

- A tutorial on how to get the country from an IP address


Say you own a fancy website ( www.example.com ) that has become quite popular globally. So, to cater the diverse needs of your visitors, you decide to customize your website for different countries. There could be various reasons to do that, for instance

  1. redirect visitors to a country specific subdomain (or path)
    e.g. https://us.example.com or https://www.example.com/us/
  2. translate the website in a specific language
  3. show country specific store locations
  4. convert product prices to another currency
  5. customize / restrict content by countries
  6. personalize with country flags, salutations etc.

This is where ipapi.co makes life easier for you. With a simple API call, you can translate the IP address of your visitor to a 2-letter country code.

Example: 
If your visitor’s IP address is 8.8.8.8, a request to ipapi.co/8.8.8.8/country will return the country code for United States i.e. US

Country code detection can go on the server side or client side, depending on your architecture. Here are some code snippets in popular languages to make the integration easier for you.

Ruby

require 'net/http'

puts Net::HTTP.get(URI('https://ipapi.co/8.8.8.8/country/'))

Python

from requests import get

print get('https://ipapi.co/8.8.8.8/country/').text

PHP

<?php
echo file_get_contents('https://ipapi.co/8.8.8.8/country/');
?>

Node.js

var https = require('https');

https.get('https://ipapi.co/8.8.8.8/country/', function(resp){
var body = ''
resp.on('data', function(data){
body += data;
});

resp.on('end', function(){
console.log(body);
});
});

jQuery

$.get('https://ipapi.co/8.8.8.8/country/', function(data){
console.log(data)
})

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class Ipapi {

public static void main(String[] args) throws IOException {
URL ipapi = new URL("https://ipapi.co/8.8.8.8/country/");

URLConnection c = ipapi.openConnection();
c.setRequestProperty("User-Agent", "java-ipapi-client");
BufferedReader reader = new BufferedReader(
new InputStreamReader(c.getInputStream())
);
String location = reader.readLine();
reader.close();

System.out.println(location);
}

}

Feel free to get in touch if you need any help !