首页 > 解决方案 > Amazon ELB + Django HTTPS 问题

问题描述

我一直在搜索 SO,但似乎没有一个解决方案适合我的情况:
我有一个来自 AWS 的 Classic Elastic Load Balancer,将请求传递给我的 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?

标签: djangodjango-rest-frameworkamazon-elb

解决方案


只需添加

proxy_set_header X-Forwarded-Proto https; 

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

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


推荐阅读