Django SSL 重定向代码段修改,未按预期工作
我使用 Nginx 作为网络服务器,并使用反向代理连接到gunicorn django 服务器。
我尝试使用这里的 SSLRedirect 代码段:
http://djangosnippets.org/snippets/85/
因为在我的设置中,此代码段始终会从 is_secure()
返回 false,从而导致重定向循环,我必须进行一些更改。
SSL 有效,但当我访问 http://domain.net/main
时,它不会重定向到 https://domain.net/main
。难道不应该这样做吗?
下面概述了我所做的修改:
if 'HTTP_X_FORWARDED_PROTOCOL' in request.META:
return True
在我的 nginx conf 中(我只需要 SSL,不需要 http):
server {
listen 8888;
server_name domain.net;
ssl on;
ssl_certificate /path/to/domain.pem;
ssl_certificate_key /path/to/domain.key;
# serve directly - analogous for static/staticfiles
location /media/ {
root /path/to/root;
}
location /static/ {
root /path/to/root;
}
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_pass http://127.0.0.1:8881/;
# note this line
proxy_set_header X-Forwarded-Protocol https;
}
}
I'm using Nginx as webserver, with a reverse proxy to a gunicorn django server.
I tried using the SSLRedirect snippet from here:
http://djangosnippets.org/snippets/85/
Because this snippet would always return false from is_secure()
with my setup, resulting in a redirect loop, I had to make some changes.
SSL works, but when I access http://domain.net/main
it doesn't redirect to https://domain.net/main
. Isn't it supposed to do that?
Below outlines the modification I made:
if 'HTTP_X_FORWARDED_PROTOCOL' in request.META:
return True
And in my nginx conf (I only need SSL, http not required):
server {
listen 8888;
server_name domain.net;
ssl on;
ssl_certificate /path/to/domain.pem;
ssl_certificate_key /path/to/domain.key;
# serve directly - analogous for static/staticfiles
location /media/ {
root /path/to/root;
}
location /static/ {
root /path/to/root;
}
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_pass http://127.0.0.1:8881/;
# note this line
proxy_set_header X-Forwarded-Protocol https;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
完全用nginx来做就可以了。根本不需要涉及 Django:
Just do it entirely with nginx. No need to involve Django at all: