これは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)
それをファイルに追加し、ミドルウェア設定でそれをポイントします。次に、2 つの設定項目を追加する必要があります。最初のものが呼び出され、次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
]
2 番目は、次のフラグである必要がありますHTTPS_SUPPORT
。
HTTPS_SUPPORT = True
その後、ユーザーが HTTP で URL にアクセスするたびSECURE_REQUIRED_PATHS
に、同等の HTTPS にリダイレクトされます。