问题简述
当flask项目经过nginx代理后,通过https访问,即使nginx设置了header X-Forwarded-Proto,但flask request中的wsgi.url_scheme仍然是http。
解决一
在url_for构造url的时候把scheme指定为header中的X-Forwarded-Proto。
url_for("xxx.xxx”, _external=True, _scheme=request.headers.get("X-Forwarded-Proto", "http")))
解决二
解决一确实可以解决问题但好像不够优雅。
另外一个则是使用ProxyFix调整代理后的WSGI的环境,使用也是非常的简单。
from werkzeug.middleware.proxy_fix import ProxyFix
app = ProxyFix(app, x_proto=1)
参考链接
Flask文档中的代理设置:https://dormousehole.readthedocs.io/en/latest/deploying/wsgi-standalone.html
Werkzeug文档中的ProxyFix:https://werkzeug.palletsprojects.com/en/master/middleware/proxy_fix/