Skip to content

Instantly share code, notes, and snippets.

@jsoa
Created August 17, 2012 14:52
Show Gist options
  • Save jsoa/3379428 to your computer and use it in GitHub Desktop.
Save jsoa/3379428 to your computer and use it in GitHub Desktop.
django redirects fallback middleware so it only matches the old path resource and not query strings.
import urlparse
from django import http
from django.conf import settings
from django.contrib.redirects.models import Redirect
class RedirectFallbackMiddleware(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()
path_qs = ''
try:
r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path)
except Redirect.DoesNotExist:
try:
parsed = urlparse.urlparse(path)
r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=parsed.path)
path_qs = parsed.query
except (Redirect.DoesNotExist, AttributeError, TypeError):
r = None
if r is None and settings.APPEND_SLASH:
# Try removing the trailing slash.
try:
r = Redirect.objects.get(site__id__exact=settings.SITE_ID,
old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:])
except Redirect.DoesNotExist:
pass
if r is not None:
if r.new_path == '':
return http.HttpResponseGone()
np = urlparse.urlparse(r.new_path)
new_qs = ((np.query and path_qs) and '?{0}&{1}'.format(np.query, path_qs)) or \
(np.query and '?{0}'.format(np.query)) or \
(path_qs and '?{0}'.format(path_qs)) or \
''
return http.HttpResponsePermanentRedirect('{0}{1}'.format(np.path, new_qs))
# No redirect was found. Return the response.
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment