简体   繁体   English

重定向到https的Django中间件

[英]Django Middleware that redirects to https

I'm trying to build some middleware in my Django project that redirects the user to a 'https' link if their request isn't initially to https. 我正在尝试在我的Django项目中构建一些中间件,如果用户的请求最初不是https,则该中间件会将用户重定向到“ https”链接。 The code below is not redirecting the user under any of the tests that I've run (ie user enters 'www.example.com', ' http://example.com ,', http://www.example.com ', etc. 下面的代码不会在我运行的任何测试下重定向用户(即用户输入“ www.example.com”,“ http://example.com ”, http://www.example.com '等

Can any of you spot the problem with this code? 你们中的任何人都能发现此代码有问题吗? Normally, I'd use print statements to see what the path is being set to, but I can't do that on my live server (or at least I don't know how to): 通常,我会使用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

Thanks again guys 再次感谢你们

You can add the following to your settings file 您可以将以下内容添加到设置文件中

SECURE_SSL_REDIRECT = True

See https://docs.djangoproject.com/en/2.1/ref/middleware/#ssl-redirect 参见https://docs.djangoproject.com/zh-CN/2.1/ref/middleware/#ssl-redirect

You'll also need to add the following to your middlewares 您还需要将以下内容添加到中间件中

'django.middleware.security.SecurityMiddleware',

It's a settings available from Django 1.8+ 这是Django 1.8+中可用的设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM