Skip to content Skip to sidebar Skip to footer

Best Way To Redirect Domain Based On Ip Address (country) In Django

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 r

Solution 1:

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.

Solution 2:

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

defcf_geo(get_response):
    defmiddleware(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

Post a Comment for "Best Way To Redirect Domain Based On Ip Address (country) In Django"