Country based redirection on nginx behind load balancer|Geo Location Based redirection
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:
- Nginx webserver. If nginx is not installed, follow the posts.
- Redirects India customer to example.in and rest of the country to example.com
- 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.