您可以在 django 级别处理此问题,这就是我使用的:
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)
将其添加到文件并使用中间件设置指向它。然后您将需要添加两个设置项。第一个被调用SECURE_REQUIRED_PATHS
,它应该是一个 URL 列表,如下所示:
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
]
第二个应该是一个名为HTTPS_SUPPORT
:
HTTPS_SUPPORT = True
然后,只要用户使用 HTTP 访问您的 URL SECURE_REQUIRED_PATHS
,他们就会被重定向到 HTTPS 等效项。