Amazon ELB + Django HTTPS 问题

psy*_*ok7 4 django amazon-elb django-rest-framework

我一直在搜索,但似乎没有一个解决方案适合我的情况:
我有一个来自 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;
    }
 }
Run Code Online (Sandbox Code Playgroud)

在我的 Django 设置中,我有:

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = False
Run Code Online (Sandbox Code Playgroud)

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

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

Tar*_*ani 6

只需添加

proxy_set_header X-Forwarded-Proto https; 
Run Code Online (Sandbox Code Playgroud)

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

$scheme另外,可能不起作用的原因是你的 nginx 仍在http协议上而不是https协议上