X-Forwarded-Proto and Flask

2019-01-14 22:24发布

I have precisely the same problem described in this SO question and answer. The answer to that question is a nice work around but I don't understand the fundamental problem. Terminating SSL at the load balancer and using HTTP between the load balancer and web/app servers is very common. What piece of the stack is not respecting the X-Forwarded-Proto? Is it werkzeug? Flask? uwsgi?

In my case I'm using an AWS ELB (which sets X-Forwarded-Proto) => Nginx (which forwards along X-Forwarded-Proto to uwsgi). But in the python app I have to subclass Flask Request as described in the question I referenced above.

Since this is such a common deployment scenario, it seems that there should be a better solution. What am I missing?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-14 22:42

You are missing the ProxyFix() middleware component. See the Flask Proxy Setups documentation.

There is no need to subclass anything; simply add this middleware component to your WSGI stack:

from werkzeug.contrib.fixers import ProxyFix
from flask import Flask


app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)

If you have Flask installed, you have Werkzeug too.

This component sets the WSGI scheme from the X-Forwarded-Proto header. Do read the Flask documentation I linked you to above about trusting headers and about customising the middleware to your specific situation.

查看更多
登录 后发表回答