Django 1.4 + python2.7
我的网站有三个域名,例如india.abc.com
,usa.abc.com
和intl.abc.com
。
现在我想要的是基于IP地址重定向的域。假设用户属于印度(IP地址)他/她应该转到india.abc.com
,如果用户在美国他/她应该转到usa.abc.com
。
请指教。这样做的最佳方式是什么?
答案 0 :(得分:0)
首先,您需要IP到LOCATION服务才能获得IP的相应位置。无论何时您拥有该服务(或基于数据库的查找算法),您都可以这样做:
# 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')