Created
November 11, 2015 11:19
-
-
Save pahaz/e1a7042242f3b440fc72 to your computer and use it in GitHub Desktop.
CheckDomainMiddleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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