2
server{
    listen 80;
    listen [::]:80;
    server_name 111.111.111.111 example.com www.example.com;
    return 301 https://example.com$request_uri;

}

I have not installed any extra NGINX libraries. I have the above server block in my sites-available default configuration which then goes to the HTTPS server block. I want to redirect Canada visitors to example.ca and all other countries to example.com. I have gotten this far but now I am not sure where else to go from here.

kabuto178
  • 121
  • 1
  • 3

1 Answers1

3

Yes, this can certainly be done. I'll assume you have the full Nginx Installation with MAP Module active.

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.

  1. wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz -O /usr/share/GeoIP/GeoLiteCity.dat.gz
  2. 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)

Hope this helps.

Ashley Primo
  • 405
  • 2
  • 10