How to implement Https(SSL Middleware) in Django

2019-05-28 22:14发布

I am a newbie in Django and web development. I want to implement Exactly this Question, but in django. I have searched many blogs and questions, nowhere was i able to find,exactly how to implement this. The SSL Middleware Django, is something i couldnt grasp very well. If that is the solution, can anyone please tell me how to implement it?

Is the question clear ? or do i need to add a few things, please comment i will make the necessary changes.Any help will be highly appreciated.Thanks in advance.

P.S: I have added the ssl certificate on the server. So that is taken care of.

2条回答
Evening l夕情丶
2楼-- · 2019-05-28 22:40

You just need to add the middleware class to the list of middleware in your settings.py and follow the instructions for your views as directed in the snippet. Here's the documentation guide to middleware.

Hope that helps you out.

查看更多
Root(大扎)
3楼-- · 2019-05-28 22:41

Here's an example middleware that redirects to the SSL site if HTTP is used:

from django.http import HttpRequest
from django.shortcuts import redirect

  #Require SSL com only. If we get anything else, redirect to https /
class RequireSSL(object):
  def process_request(self, request):
    assert isinstance( request, HttpRequest )
    if not request.is_secure():
      return redirect( 'https://%s/' % request.get_host() )

Then inside your settings.py:

MIDDLEWARE_CLASSES = [
    'website.middleware.require_ssl.RequireSSL',
    ...
]
查看更多
登录 后发表回答