You can handle this at the django level, this is what I use:
from django.http import HttpResponsePermanentRedirect
from django.conf import settings
class SecureRequiredMiddleware(object):
def __init__(self):
self.paths = getattr(settings, 'SECURE_REQUIRED_PATHS')
self.enabled = self.paths and getattr(settings, 'HTTPS_SUPPORT')
def process_request(self, request):
if self.enabled and not request.is_secure():
full_path = request.get_full_path()
for path in self.paths:
if full_path.startswith(path):
secure_url = request.build_absolute_uri(full_path).replace(
'http://', 'https://')
return HttpResponsePermanentRedirect(secure_url)
Add that to a file and point to it with your middleware settings. Then you will need to add two settings items. The first is called SECURE_REQUIRED_PATHS
and it should be a list of URL's like so:
SECURE_REQUIRED_PATHS = [
'/login', # require HTTPS for any URL starting with `/login`
'/account', # require HTTPS for any URL starting with `/account`
'/', # require HTTPS for all URLs
]
The second should be a flag called HTTPS_SUPPORT
:
HTTPS_SUPPORT = True
Then anytime a user access a URL in your SECURE_REQUIRED_PATHS
with HTTP, they will be redirected to the HTTPS equivalent.