在 Django 中,当启用 SSL 时,如果通过 request.getScheme() 得到的仍然是 http,而不是 https,通常是因为 Django 对 getScheme() 方法的行为依赖于 X-Forwarded-Proto 请求头,而默认情况下,Django 并不信任该头信息。

因此需要在 Django 的 settings.py 中配置:

1
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

但此时,出现了 Django Admin 页面登录时报错 Forbidden (403) CSRF verification failed. Request aborted.,按照 GPT 给出的各种配置都尝试了均无效,最终问题还是出在 nginx 的配置上。要特别注意一点:

注意

如果你之前配置了 Host 包含端口号 $host:$server_port,可以尝试修改为仅 $host,因为某些情况下端口号可能会干扰 Host 校验。

检查 nginx 配置,发现果然有这一项配置 proxy_set_header Host $host:$server_port; 当去掉端口号后,问题就解决了。

最后放出 django 项目的 nginx 完整配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
server {
    listen 80;
    server_name challenge.aisafety.org.cn;
    return 301 https://challenge.aisafety.org.cn$request_uri;
}

server {
    listen 443 ssl;
    server_name challenge.aisafety.org.cn;
    client_max_body_size 500M;

    ssl_certificate /root/.acme.sh/challenge.aisafety.org.cn/fullchain.cer;
    ssl_certificate_key /root/.acme.sh/challenge.aisafety.org.cn/challenge.aisafety.org.cn.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES128+AESGCM:AES256+AESGCM:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    location / {
        proxy_pass http://127.0.0.1:8010;
        proxy_set_header Host $host;    # !!!就是这里,不要加:$server_port
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
        add_header Cache-Control "no-cache, no-store";
    }

    location /statics/ {
        alias /data/data2/aisafety-tech-django/statics/;
        access_log off;
        expires 1y;
        add_header Cache-Control "public";
    }

    location /media/ {
        alias /data/data2/aisafety-tech-django/media/;
        access_log off;
        expires 1y;
        add_header Cache-Control "public";
    }

    location /flower {
        proxy_pass http://127.0.0.1:5566/;
        proxy_set_header Host $host;
    }
    location /dashboard {
        proxy_pass http://127.0.0.1:5566/dashboard;
        proxy_set_header Host $host;
    }
    location /tasks {
        proxy_pass http://127.0.0.1:5566/tasks;
        proxy_set_header Host $host;
    }
    location /broker {
        proxy_pass http://127.0.0.1:5566/broker;
        proxy_set_header Host $host;
    }
}