Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.