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 ( ) 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 or
  2. Set a default website for visitors from a location e.g. visitors outside US are redirected to
  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.

If your visitor’s IP address is, a request to 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.


require 'net/http'

puts Net::HTTP.get(URI(''))


from requests import get

print get('').text


echo file_get_contents('');


var https = require('https');

https.get('', function(resp){
var body = ''
resp.on('data', function(data){
body += data;

resp.on('end', function(){


$.get('', function(data){



public class Ipapi {

public static void main(String[] args) throws IOException {
URL ipapi = new URL("");

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



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