【问题标题】:Nginx, gunicorn, python-flask application. Https is lost on redirectNginx、gunicorn、python-flask 应用程序。重定向时 Https 丢失
【发布时间】:2016-05-10 19:52:42
【问题描述】:

我的申请遇到了一些问题。在重定向期间,我的烧瓶应用程序丢失了 https 并改为重定向到 http。

我一直在努力寻找解决方案,但没有任何效果。

我的应用程序(位置/)的nginx配置如下:

proxy_pass http://localhost:5400;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-port 443;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

(互联网上的一些示例说使用“X-Forwarded-Proto”。我已经尝试过但没有成功。并且还使用“ssl”或“https”作为该参数的值。

烧瓶应用程序(before_request :) 中的简单打印表明,尽管我在客户端和 nginx 之间使用 https,但它仍然是 http-requests 发出的事件。

print(request.environ["wsgi.url_scheme"])

我做错了什么?

【问题讨论】:

  • 你解决了吗?

标签: redirect nginx https flask gunicorn


【解决方案1】:

警告。进行不需要的 HTTP 重定向是一个安全漏洞,因为在这些请求中连接未加密!!

这里唯一的解决方案是正确配置 NGINX 和 GUNICORN 以允许 Flask 使用正确的标头。

NGINX 配置应至少包含以下指令:

proxy_set_header        Host $host;
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-Forwarded-Host $http_host;
proxy_pass              http://appserver:5000;

而且,这是真正的解决方案,GUnicorn 必须以 --forwarded-allow-ips 参数开头。

以下是我如何在生产中启动它,同时在日志中修复真实 IP 地址(小心向 GDPR 投诉:P):

PYTHONUNBUFFERED=FALSE gunicorn              \
                        --access-logfile '-' \
                        --access-logformat '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" "%({X-Real-IP}i)s"' \
                        -b :5000             \
                        --forwarded-allow-ips="*" \
                        app:app

您应该绝不在 HTTP 中发送请求。第一个也是唯一的重定向应该是/

【讨论】:

    【解决方案2】:

    如果您的应用程序忽略了在 http 3xx 响应中设置方案的 X-Forwarded 标头,您可以尝试设置一个或多个 proxy_redirect 规则:

    proxy_redirect http:// $scheme://;
    

    详情请见this document

    【讨论】:

      猜你喜欢
      • 2019-03-07
      • 2023-03-31
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 2021-08-27
      • 2011-11-12
      • 2020-12-14
      相关资源
      最近更新 更多