[Answer]-Site enters into Redirect loop when using HTTP HttpResponsePermanentRedirect in django middleware

1👍

You are always redirecting people from India and Netherlands, there’s a loop because there’s no breaking from it. You should do the redirection only when request.path is not /en/ or /nl/.

def process_request(self, request):
    # NOTICE: This will make sure redirect loop is broken.
    if request.path in ["/en/", "/nl/"]:
        return None
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        request.META['REMOTE_ADDR'] = request.META['HTTP_X_FORWARDED_FOR']
    ip = request.META['REMOTE_ADDR']
    print request.path
    country = get_country_request(ip)             
    if country == "India":
        return HttpResponsePermanentRedirect('/en/')       
    if country == "Netherlands":
        return HttpResponsePermanentRedirect('/nl/')
    return None
👤tayfun

Leave a comment