Skip to content

Instantly share code, notes, and snippets.

@pahaz
Created November 11, 2015 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pahaz/e1a7042242f3b440fc72 to your computer and use it in GitHub Desktop.
Save pahaz/e1a7042242f3b440fc72 to your computer and use it in GitHub Desktop.
CheckDomainMiddleware
class CheckDomainMiddleware(object):
"""
If MULTISITE_WRONG_DOMAIN_REDIRECT_URL defined all wrong domain requests
will be redirected to this url. Otherwise Http 404 will be returned.
How-to use:
# 1. add to MIDDLEWARE_CLASSES
# 2. File: settings.py
MULTISITE_WRONG_DOMAIN_REDIRECT_URL = "http://example.com/"
"""
def process_request(self, request):
request_host = request.get_host() # with port: 127.0.0.1:8000
site_id, site_domain = get_thread_local_site_id_domain() # noqa: unused variable
if request_host != site_domain:
if settings.DEBUG and request_host.startswith('127.0.0.1'):
log.warning('CheckDomainMiddleware skip wrong host: real {}, '
'expect {}'.format(request_host, site_domain))
return
url = getattr(settings, 'MULTISITE_WRONG_DOMAIN_REDIRECT_URL', '')
if not url:
raise Http404('No redirects for this domain. '
'CheckDomainMiddleware raise Http404 for this '
'request')
return HttpResponseRedirect(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment