Automatically redirect visitors to country or city specific page

A tutorial on how to get the location from an IP address and use it to redirect your users to a region specific website.

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

  1. Redirect your website users to a country specific subdomain (or path), e.g. send all users from UK to uk.example.com or example.com/uk
  2. Set a default website for visitors from a location e.g. visitors outside US are redirected to global.example.com
  3. Translate the website in a specific language
  4. Show area specific store locations
  5. Convert product prices to another currency
  6. Customize / restrict content by countries
  7. Personalize with country flags, salutations etc.

This is where ipapi 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 !

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store