With the full Nginx Installation with MAP Module active You can redirect based on GEOIP.
You will need the geoip-database
installed, on RedHat based system with YUM you will use the following:
yum install geoip geoip-devel
So once you have that installed you will need MaxMind’s City database which can be retrieved from MaxMind’s website.
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz -O /usr/share/GeoIP/GeoLiteCity.dat.gz
gunzip /usr/share/GeoIP/GeoLiteCity.dat.gz
So now you have the setup out the way you are ready to configure NGINX, which is relatively straightforward.
The example configuration for your case would go something like the following:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
map $geoip_city_country_code $nearest_server {
default example.com;
CA example.ca;
}
server{
listen 80;
listen [::]:80;
server_name example.com
example.ca;
if ($nearest_server != $host) {
rewrite ^ $scheme://$nearest_server$request_uri break;
}
}
}
So, specifics: In the configuration above it does depend on your installation so you’ll need to ensure that the include, error_log and pid directory is correct to your installation and preference.
In respect of how it works, I believe it’s pretty self-explanatory however to delve into it a bit:
geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
> links the downloaded MaxMind GeoIP city data to NGINX.
map $geoip_city_country_code $nearest_server {
default example.com;
CA example.ca;
}
The above section links your multiple hosts, and their respective country code, e.g. CA for Canada- you can add as many entries as you want.
if ($nearest_server != $host) {
rewrite ^ $scheme://$nearest_server$request_uri break;
}
The above section decides what server based to use based on location, and passes on the request URI. Example http://example.com/store.php
requested from a Canadian IP will redirect to http://example.ca/store.php
That is pretty much it, the main sections are the MAP section, and the IF statement within the server component (and fulfilment of the requirements)