django - 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?
解决方案
只需添加
proxy_set_header X-Forwarded-Proto https;
在你的 nginx 配置中。您的 nginx 将始终使用 https 为客户端提供服务,因为 ELB 已配置为接收https
流量。
另外原因$scheme
可能不起作用是因为您的 nginx 仍然在http
协议而不是https
协议上
推荐阅读
- ios - 当 Rails 解析其提交的参数时,SwiftUI 总是将字段值提交为 Optional
- c# - 插入值后刷新 DataGridView
- sql-server - SQL Server 未捕获链接服务器超时错误
- ios - UISplitViewController - 在 iPad Portrait 中展开和折叠主视图
- python - 为什么列表推导不适用于使用等号更新字典元素
- pandas - 回填和增量一?
- swift - 在将 textField 传递给函数之前如何测试它是否为空:
- python - 当 content_type 是字典时,单元测试很热门
- node.js - 大文件不会传输到 Elastic Beanstalk 托管应用程序
- javascript - 覆盖 JS 原型函数