Question

I am getting redirect loop with this code in my website when I try to deploy on Heroku. Here is the code for the middleware

# -*- coding: utf-8 -*-

from django.utils.functional import SimpleLazyObject
from django.conf import settings
from django.http import HttpResponsePermanentRedirect

def get_country_request(ip):
   import pygeoip
   file_path = settings.PROJECT_ROOT + '/data/GeoIP.dat.dat'
   gi = pygeoip.GeoIP(file_path)
   country = gi.country_name_by_addr(ip)   
   if country:
      return country

class LocationMiddleWare(object):


    def process_request(self, request):
        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

Please suggest where did I do wrong and suggest if there is a better approach.

Thanks in advance!

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top