django 301 Moved Permanently Middleware

By youbbs at 2015-06-29 10:31:14 • 482次点击

django 301 转向中间件

from django.conf import settings
from django.core.urlresolvers import is_valid_path
from django.http import HttpResponsePermanentRedirect
from django.middleware.locale import LocaleMiddleware
from django.utils import translation
from django.utils.cache import patch_vary_headers

class UrlRedirectMiddleware(object):
    This middleware lets you match a specific url and redirect the request to a
    new url. You keep a tuple of (regex pattern, redirect) tuples on your site
    settings, example:

        (r'(https?)://(www\.)?sample\.com/(.*)$', r'\1://\3'),
    def process_request(self, request):
        full_url = request.build_absolute_uri()
        for url_pattern, redirect in settings.URL_REDIRECTS:
            match = re.match(url_pattern, full_url)
            if match:
                return HttpResponsePermanentRedirect(match.expand(redirect))

在settings MIDDLEWARE_CLASSES 里加入上面的中间件,如



import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()

def application(environ, start_response):
  if environ['HTTP_HOST'] != '':
    start_response('301 Redirect', [('Location', ''),])
    return []
  return _application(environ, start_response)

django, moved, permanently, middleware

登录 后发表评论