Amazon ELB + Django HTTPS 问题

Amazon ELB + Django HTTPS issues

我一直在搜索 SO,但 none 的解决方案似乎适用于我的情况:
我有一个来自 AWS 的经典弹性负载均衡器,将请求传递到我的 Nginx docker 容器,这些容器也代理传递到我的 python Gunicorn 容器。

Nginx 配置:

server {
    listen 80;
    listen [::]:80;
    ...

    if ($http_x_forwarded_proto = 'http') {
        return 301 https://$server_name$request_uri;
    }

    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-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://app_server;
    }
 }

在我的 Django 设置中我有:

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = False

问题是,当向端点发出请求时,如果我 print(request.META.get('HTTP_X_FORWARDED_PROTO')) 我得到 http 而不是 https。这导致我的 DRF 自动生成的文档链接在 http 而不是 https.

中生成

我的配置有问题吗?
如何在 ELB 后面强制使用 https?

只需添加

proxy_set_header X-Forwarded-Proto https; 

在你的 nginx 配置中。您的 nginx 将始终使用 https 为客户端提供服务,因为 ELB 配置为接收 https 流量。

此外,$scheme 可能不起作用的原因是因为您的 nginx 仍在使用 http 协议而不是 https 协议

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 $proxy_x_forwarded_proto;