Skip to content

Instantly share code, notes, and snippets.

@nrm176
Created November 26, 2019 05:21
Show Gist options
  • Save nrm176/c2f07880d419d2bd136c1f8e93284469 to your computer and use it in GitHub Desktop.
Save nrm176/c2f07880d419d2bd136c1f8e93284469 to your computer and use it in GitHub Desktop.
Django middleware
from django.http import HttpResponsePermanentRedirect
from django.utils.deprecation import MiddlewareMixin
class RedirectHostMiddleware(MiddlewareMixin):
def process_request(self, request):
host = request.get_host()
if host and host.startswith('www.'):
redirect_url = '%s://%s%s' % (
request.scheme, host[4:], request.get_full_path()
)
return HttpResponsePermanentRedirect(redirect_url)
if host and ('herokuapp' in host):
my_domain = 'example.com'
redirect_url = '%s://%s%s' % (
request.scheme, my_domain, request.get_full_path()
)
return HttpResponsePermanentRedirect(redirect_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment