Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 518
Alireza Seifi Avatar asked Jan 31 '26 17:01

Alireza Seifi


2 Answers

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.
like image 145
Christian Ternus Avatar answered Feb 02 '26 05:02

Christian Ternus


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

like image 36
TomRavn Avatar answered Feb 02 '26 06:02

TomRavn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!