3

We have 2 stores which are XXXXXX.com and XXXXXX.com.mx, I'd like to allow only US IPs go to XXXXXX.com any other IPs need to route to XXXXXX.com.mx

We used to use Limelight for routing but we're no longer using them then we decided to do it by ourself. now we're looking for a fastest and best way to route customers based on GEO-ip.

The way the rules were set in Limelight, if Country was not US or IN and the request was .XXXXXX.com/, then route to www.XXXXXX.com.mx.

Alireza Seifi
  • 135
  • 3
  • 11
  • I have no a complete answer, however, you have to use a GEO database service such as http://www.ipligence.com/ – SaidbakR Oct 16 '13 at 21:46

2 Answers2

3

You have a few options.

  • Use something like geoip-redirect, a prebuilt library for doing approximately this.
  • Use a third-party library such as django-geoip, then check for the user location in your landing page and do a redirect.
  • Use django.contrib.gis.geoip to code up your own solution similar to the above.
Christian Ternus
  • 8,406
  • 24
  • 39
1

I know this question is old, but I was solving this recently in Django 3.1.4 too. This method depends on Cloudflare CDN, because Cloudflare has option to add GEO location header into all requests.

enter image description here

Cloudflare uses country format ISO 3166-1 Alpha 2, which can be found here on wikipedia.

In Django we can retrieve country code like this:

country = request.META.get('HTTP_CF_IPCOUNTRY') 

For successful redirection we can use custom Django middleware like this:

from django.shortcuts import redirect

def cf_geo(get_response):
    def middleware(request):
        response = get_response(request)
        country = request.META.get('HTTP_CF_IPCOUNTRY') 
        #https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
        redirected_geos = ['AF','AL','AZ','BD','BH','CD','CF','CG','DZ','ET','ER','GH','KE','KZ','MG','MZ','NA','NE','NG','PK','SD','SO','SS','UG','UZ','ZM','ZW','XX']       
        if country in redirected_geos:
            return redirect('https://google.com')
        return response
    return middleware

I find this combination with Cloudflare really easy, because I don't have to install any extra library or make any extra API call.

Cloudflare is using a few extra codes 'XX' = unknown country 'T1' = people who use Tor network

TomRavn
  • 1,134
  • 14
  • 30