youbbs avatar

django 301 Moved Permanently Middleware

🕞 by youbbs

django 301 转向中间件

middleware.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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:

    URL_REDIRECTS = (
        (r'(https?)://(www\.)?sample\.com/(.*)$', r'\1://example.com/\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 里加入上面的中间件,如

1
myapp.middleware.UrlRedirectMiddleware

还有一种更简单的方式

1
2
3
4
5
6
7
8
import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()

def application(environ, start_response):
  if environ['HTTP_HOST'] != 'www.example.com':
    start_response('301 Redirect', [('Location', 'http://www.example.com/'),])
    return []
  return _application(environ, start_response)

💘 相关文章

写一条评论

Based on Golang + fastHTTP + sdb | go1.16.3 Processed in 1ms