-1

Django 1.4 + python2.7

I have a website which has three domains let say india.abc.com, usa.abc.com and intl.abc.com. Now what i want is based on IP Address the domains to be redirected. Let say if the user belongs to India (IP Address) he/she should go to india.abc.com , if the user is in US he/she should go to usa.abc.com.

Please advice. What is the best way to do this?

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
djangobot
  • 257
  • 1
  • 2
  • 11

1 Answers1

0

First you need an IP to LOCATION service to get the IP's corresponding location. Whenever you have that service (or database based lookup algorithm) then you could do this:

# got from here: http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

def get_ip_location(ip):
    # here you need to invoke a IP to location service, or implement your own.
    # It's not that hard. Start here: http://stackoverflow.com/questions/4179000/best-way-to-detect-country-location-of-visitor
    pass

def index(request):
    ip = get_client_ip(request)
    location = get_ip_location(ip)
    if location == 'usa':
        return redirect('http://usa.abc.com')
    elif location == 'japan':
        return redirect('http://jpn.abc.com')
    # you get the idea
    else:
        return redirect('http://global.abc.com')
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • Thanks for helping me out. Can you tell me how would i do this for the entire project. I don't want to do this individual function. – djangobot Aug 17 '14 at 14:02