from django.contrib.redirects.models import Redirect from django import http from django.conf import settings import re class RegExRedirectFallbackMiddleware(object): def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a redirect for non-404 responses. path = request.get_full_path() redirects = Redirect.objects.filter(site__id__exact=settings.SITE_ID) for r in redirects: try: old_path = re.compile(r.old_path, re.IGNORECASE) except re.error: # old_path does not compile into regex, ignore it and move on to the next one continue if re.match(r.old_path, path): new_path = r.new_path.replace('$', '\\') replaced_path = re.sub(old_path, new_path, path) return http.HttpResponsePermanentRedirect(replaced_path) # Return the response. return response