【问题标题】:How can I prevent a redirect loop using SSL with gunicorn/nginx?如何使用带有 gunicorn/nginx 的 SSL 防止重定向循环?
【发布时间】:2012-11-26 14:06:17
【问题描述】:

使用 SSL 中间件将某些 URL 重定向到 HTTPS 时,我得到一个重定向循环。我该怎么办?

我的 nginx 配置设置为将请求转发到 gunicorn。

【问题讨论】:

    标签: django nginx gunicorn django-middleware


    【解决方案1】:

    这里有几个步骤。

    首先,修改中间件检查 SSL 的方式:

      def _is_secure(self, request):
        if request.is_secure():
          return True
    
        if 'HTTP_X_SSL_PROTOCOL' in request.META:
          return True
    
        return False
    

    然后按如下方式更改您的 nginx 配置:

    server {
        listen 80;
        listen 443 ssl;
    
        ...
    
        location / {
    
            ...
            proxy_set_header X-SSL-Protocol $ssl_protocol;
            proxy_pass http://localhost:8000/;
        }
    }
    

    proxy_set_header 只会在 ssl_protocol 不为 null 时被传递,也就是说,它是一个安全连接。

    重启nginx就完成了。

    【讨论】:

    • 从 django 1.4 开始,您不需要自定义中间件,因为它是内置的。另见SECURE_PROXY_SSL_HEADER。顺便说一句,nginx 的好技巧。
    【解决方案2】:

    添加到汤姆的答案。如果您使用 Heroku 或其他负载均衡器,以下内容可能也会有所帮助。

    def _is_secure(self, request):
        if request.is_secure():
          return True
    
        if 'HTTP_X_SSL_PROTOCOL' in request.META:
          return True
    
        # check the forwarded request's protocol
        if request.META.get('HTTP_X_FORWARDED_PROTO')=='https':
            return True
    
        return False
    

    【讨论】:

      猜你喜欢
      • 2014-06-01
      • 2019-09-20
      • 2015-02-26
      • 2015-02-15
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      相关资源
      最近更新 更多