【发布时间】:2012-11-26 14:06:17
【问题描述】:
使用 SSL 中间件将某些 URL 重定向到 HTTPS 时,我得到一个重定向循环。我该怎么办?
我的 nginx 配置设置为将请求转发到 gunicorn。
【问题讨论】:
标签: django nginx gunicorn django-middleware
使用 SSL 中间件将某些 URL 重定向到 HTTPS 时,我得到一个重定向循环。我该怎么办?
我的 nginx 配置设置为将请求转发到 gunicorn。
【问题讨论】:
标签: django nginx gunicorn django-middleware
这里有几个步骤。
首先,修改中间件检查 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就完成了。
【讨论】:
添加到汤姆的答案。如果您使用 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
【讨论】: