python - Django SSL Redirect 片段修改,未按预期工作

标签 python django ssl nginx

我使用 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; 
}
}

最佳答案

只需完全使用 nginx 即可。根本不需要涉及 Django:

server {
    listen 80;
    rewrite ^(.*) https://$host$1 permanent;
}

server {
    listen 443;
    # The rest of your original server config here
}

关于python - Django SSL Redirect 片段修改,未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9265824/

相关文章:

python - Tango with Django (v1.9/1.10) - 第 5 章,populate_rango 问题

ssl - meteor - 我如何使用 tarang :ssl correctly?

ssl - noVNC websockify ssl

ssl - 带有 Windows-My 或 Windows-ROOT 证书的 Jboss/Wildfly SSL

python - Pynput 监听器不允许包含字母数字字符的 if 语句

python - jinja2:按定义的键顺序对字典进行排序?

python - 如何使用每个离散值的条形图创建条形图/直方图?

Django Rest 框架电子邮件验证

python - 本地测试 GAE-python27-django 项目

javascript - 在javascript中迭代Django模板变量,通过变化的索引进行访问