Country based redirection on nginx behind load balancer|Geo Location Based redirection

Date Posted: 19-12-2017

There are scenario where we want to setup country based redirection depends on visitor. In this post, we will explain on how to setup country based redirection on nginx which is behind load balancer.

Assumption:

  1. Nginx webserver. If nginx is not installed, follow the posts.
    1. Ubuntu 16.04
    2. Centos 7
  2. Redirects India customer to example.in and rest of the country to example.com
  3. Webserver is behind the load balancer.

Implementation:

If you followed our previous articles then the default configuration path will be /etc/nginx/nginx.conf and domain configuration will be /etc/nginx/sites-enabled/default.conf

Open the nginx configuration and add the below lines under http section

vi /etc/nginx/nginx.conf

real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
geoip_country /usr/share/GeoIP/GeoIP.dat;

Please make sure that the file /usr/share/GeoIP/GeoIP.dat exists.

Where,

The X-Forwarded-For and X-Real-IP directives in the above config will properly forward the Client IP from the Nginx server.

real_ip_recursive to on will return the leftmost (original) IP instead of the rightmost (most recent) IP from the X-Forwarded-For header.

Open the site configuration file(default config is /etc/nginx/sites-enabled/default.conf) and append the below line inside the server  block.

vi /etc/nginx/sites-enabled/default.conf

if ($geoip_country_code = IN){
return 301 http://example.in;
}

The above line will redirect the traffic to example.in incase if the traffic is generating from India.

Verify the nginx syntax

nginx -t

Restart the nginx service.

service nginx restart

Access the domain or IP address from India and the request will be redirected to example.in.

 

Leave a Reply