[Django]-Best way to redirect domain based on ip address (country) in Django

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.

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

Leave a comment