【问题标题】:I.P. based redirect different domains of same websites知识产权基于重定向同一网站的不同域
【发布时间】:2014-08-17 12:58:53
【问题描述】:

Django 1.4 + python2.7

我有一个网站,它有三个域,比如说india.abc.comusa.abc.comintl.abc.com。 现在我想要的是基于 IP 地址来重定向域。假设用户属于印度(IP 地址),他/她应该去india.abc.com,如果用户在美国,他/她应该去usa.abc.com

请指教。最好的方法是什么?

【问题讨论】:

    标签: django


    【解决方案1】:

    首先你需要一个IP to 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')
    

    【讨论】:

    • 感谢您帮助我。你能告诉我我将如何为整个项目做这件事吗?我不想做这个单独的功能。
    猜你喜欢
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2010-09-22
    • 2013-12-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多