2006-05-02 09:31:56 +08:00
|
|
|
from django.contrib.redirects.models import Redirect
|
|
|
|
from django import http
|
|
|
|
from django.conf import settings
|
2005-11-11 12:45:05 +08:00
|
|
|
|
|
|
|
class RedirectFallbackMiddleware:
|
|
|
|
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()
|
|
|
|
try:
|
2006-05-02 09:31:56 +08:00
|
|
|
r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path)
|
|
|
|
except Redirect.DoesNotExist:
|
2005-11-11 12:45:05 +08:00
|
|
|
r = None
|
2006-05-02 09:31:56 +08:00
|
|
|
if r is None and settings.APPEND_SLASH:
|
2005-11-11 12:45:05 +08:00
|
|
|
# Try removing the trailing slash.
|
|
|
|
try:
|
2006-05-02 09:31:56 +08:00
|
|
|
r = Redirect.objects.get(site__id__exact=settings.SITE_ID,
|
|
|
|
old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:])
|
|
|
|
except Redirect.DoesNotExist:
|
2005-11-11 12:45:05 +08:00
|
|
|
pass
|
|
|
|
if r is not None:
|
|
|
|
if r == '':
|
2006-05-02 09:31:56 +08:00
|
|
|
return http.HttpResponseGone()
|
|
|
|
return http.HttpResponsePermanentRedirect(r.new_path)
|
2005-11-11 12:45:05 +08:00
|
|
|
|
|
|
|
# No redirect was found. Return the response.
|
|
|
|
return response
|