在Nginx中为Django强制HTTPS

时间:2013-05-03 06:19:26

标签: django nginx django-admin

我试过这样做:

  1. 在与settings.py
  2. 相同的目录中创建名为middleware.py(chmod 775,chown www-data)的文件
  3. 将其粘贴到middleware.py: http://djangosnippets.org/snippets/880/
  4. 将其粘贴到我的settings.py:

    MIDDLEWARE_CLASSES = ( #...
        'djo.middleware.SSLRedirect',
    )
    
    SSL_ENABLED = True
    SSL_URLS = (
        r'/admin/',
    )
    
  5. 我得到:内部服务器错误

    显示的开发服务器中没有错误。

    建议?

1 个答案:

答案 0 :(得分:0)

发现问题。我发生了无限循环,并按照此网站进行修复:

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

基本上,将此添加到文件的代理位置部分下的nginx服务器conf设置中:

SECURE_PROXY_SSL_HEADER = (‘HTTP_X_FORWARDED_PROTOCOL’, $scheme)

然后添加到您的django设置文件中:

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

ROOT_URLCONF = 'djo.urls'

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

然后在名为“middleware.py”的同一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():
            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

瞧!重定向所需的任何基本网址。