Proxyの背後にいることのFlaskへの指示 Tell Flask it is Behind a Proxy

リバースプロキシまたは多くのPythonのホスティング・プラットフォームを使っているとき、プロキシは外部のリクエストを全て、途中でとらえてローカルのWSGIサーバへ転送します When using a reverse proxy, or many Python hosting platforms, the proxy will intercept and forward all external requests to the local WSGI server.

WSGIサーバとFlaskアプリケーションの観点からは、リクエストはこの時点では、外部から見えるサーバアドレスに来たリモートのアドレス(訳注: クライアントのIPアドレスのこと)からではなく、ローカルのアドレスのHTTPサーバ(訳注: リバースプロキシのこと)からやって来ます。 From the WSGI server and Flask application's perspectives, requests are now coming from the HTTP server to the local address, rather than from the remote address to the external server address.

HTTPサーバは、本当の値をFlaskアプリケーションへ渡すためにX-Forwarded-ヘッダーを設定するべきです。Werkzeugにより提供されるX-Forwarded-For Proxy Fixミドルウェアを使ってそのヘッダーを包むことで、Flaskアプリケーションはそれらの値が信頼できると伝えられ使用できるようになります。 HTTP servers should set ``X-Forwarded-`` headers to pass on the real values to the application. The application can then be told to trust and use those values by wrapping it with the :doc:`werkzeug:middleware/proxy_fix` middleware provided by Werkzeug.

アプリケーションが実際にプロキシの背後にある場合だけ、このミドルウェアは使用されるべきあり、そしてアプリケーションの前面に連鎖しているプロキシの数を使って設定されるべきです。すべてのプロキシが全てのヘッダーを設定するわけではありません。受信するヘッダーが偽装される可能性があるため、何を信頼するべきかミドルウェアが知るために、各ヘッダーをいくつのプロキシが設定するかを設定する必要があります。 This middleware should only be used if the application is actually behind a proxy, and should be configured with the number of proxies that are chained in front of it. Not all proxies set all the headers. Since incoming headers can be faked, you must set how many proxies are setting each header so the middleware knows what to trust.

from werkzeug.middleware.proxy_fix import ProxyFix

app.wsgi_app = ProxyFix(
    app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1
)

プロキシの背後にある場合だけこのミドルウェアを適用し、各ヘッダーを設定するプロキシの数を正しく設定することを覚えておいてください。この設定が誤っている場合、セキュリティ上の問題になる可能性があります。 Remember, only apply this middleware if you are behind a proxy, and set the correct number of proxies that set each header. It can be a security issue if you get this configuration wrong.