简体   繁体   English

在Django的Nginx中强制使用HTTPS

[英]Force HTTPS in Nginx for Django

I have tried to do this: 我试图做到这一点:

  1. Create a file named middleware.py (chmod 775, chown www-data) in the same directory as my settings.py 在与settings.py相同的目录中创建一个名为middleware.py的文件(chmod 775,chown www-data)。
  2. Paste this in middleware.py: http://djangosnippets.org/snippets/880/ 将此粘贴到middleware.py中: http : //djangosnippets.org/snippets/880/
  3. Paste this in my settings.py: 将此粘贴到我的settings.py中:

     MIDDLEWARE_CLASSES = ( #... 'djo.middleware.SSLRedirect', ) SSL_ENABLED = True SSL_URLS = ( r'/admin/', ) 

I get: Internal Server Error 我得到: 内部服务器错误

No errors in the development server shown. 在开发服务器中未显示任何错误。

Suggestions? 有什么建议吗?

Found the problem. 找到了问题。 I had an infinite loop happening and followed this site to fix it: 我发生了无限循环,并按照此站点进行了修复:

http://yuji.wordpress.com/2008/08/15/django-nginx-making-ssl-work-on-django-behind-a-reverse-proxy/#comment-1941 http://yuji.wordpress.com/2008/08/15/django-nginx-making-ssl-work-on-django-behind-a-reverse-proxy/#comment-1941

Basically, add this to the nginx server conf setting under the proxy location part of the file: 基本上,将其添加到文件的代理位置部分下的nginx服务器conf设置中:

SECURE_PROXY_SSL_HEADER = (‘HTTP_X_FORWARDED_PROTOCOL’, $scheme)

Then add to your django settings file: 然后添加到您的Django设置文件中:

MIDDLEWARE_CLASSES = (...
'djo.middleware.SecureRequiredMiddleware',
)

ROOT_URLCONF = 'djo.urls'

HTTPS_SUPPORT = True
SECURE_REQUIRED_PATHS = (
    r'/admin/',

Then create a file in the same django directory called "middleware.py" with the following contents: 然后在相同的django目录中创建一个文件,该文件名为“ middleware.py”,内容如下:

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():
            for path in self.paths:
                if request.get_full_path().startswith(path):
                    request_url = request.build_absolute_uri(request.get_full_path())
                    secure_url = request_url.replace('http://', 'https://')
                    print self.paths, request_url, secure_url
                    return HttpResponsePermanentRedirect(secure_url)
        return None

Voilá! 瞧! Redirects for any base url desired. 重定向所需的任何基本URL。

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

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