我正在尝试在我的Django项目中构建一些中间件,将用户重定向到“https'如果他们的请求最初不是https,请链接。以下代码不会在我运行的任何测试下重定向用户(即用户输入' www.example.com',' http://example.com,&#39 ;,http://www.example.com'等
你们有没有发现这个代码的问题?通常情况下,我会使用print语句查看路径设置的内容,但我无法在我的实时服务器上执行此操作(或者至少我不知道如何):
from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
class RedirectMiddleware(MiddlewareMixin):
def process_request(self, request):
host = request.get_host()
if host == 'www.example.com' or 'example.com':
path = request.build_absolute_uri()
domain_parts = path.split('.')
if domain_parts[0] == 'http://www':
path = path.replace("http://www","https://www")
return HttpResponseRedirect(path)
elif domain_parts[0] == 'www':
path = path.replace("www","https://www")
return HttpResponseRedirect(path)
elif domain_parts[0] == 'http://example':
path = path.replace("http","https")
return HttpResponseRedirect(path)
elif domain_parts[0] == 'example':
path = path.replace("example","https://www.example")
return HttpResponseRedirect(path)
else:
pass
else:
pass
再次感谢你们