Skip to content

Instantly share code, notes, and snippets.

@SuAlvarez
Created March 21, 2012 05:09
Show Gist options
  • Save SuAlvarez/2144632 to your computer and use it in GitHub Desktop.
Save SuAlvarez/2144632 to your computer and use it in GitHub Desktop.
import re
from django.http import HttpResponsePermanentRedirect
from django.conf import settings
class UrlRedirectMiddleware:
"""
This middleware lets you match a specific url and redirect the request to a
new url.
You keep a tuple of url regex pattern/url redirect tuples on your site
settings, example:
URL_REDIRECTS = (
(r'www\.example\.com/hello/$', 'http://hello.example.com/'),
(r'www\.example2\.com/$', 'http://www.example.com/example2/'),
)
"""
def process_request(self, request):
host = request.META['HTTP_HOST'] + request.META['PATH_INFO']
for url_pattern, redirect_url in settings.URL_REDIRECTS:
regex = re.compile(url_pattern)
if regex.match(host):
return HttpResponsePermanentRedirect(redirect_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment