X-Forwarded-For Proxy Fix
This module provides a middleware that adjusts the WSGI environ based onX-Forwarded-
headers that proxies in front of an application mayset.
When an application is running behind a proxy server, WSGI may see therequest as coming from that server rather than the real client. Proxiesset various headers to track where the request actually came from.
This middleware should only be applied if the application is actuallybehind such a proxy, and should be configured with the number of proxiesthat 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 aresetting each header so the middleware knows what to trust.
- class
werkzeug.middleware.proxyfix.
ProxyFix
(_app, num_proxies=None, x_for=1, x_proto=1, x_host=0, x_port=0, x_prefix=0) Adjust the WSGI environ based on
X-Forwarded-
that proxies infront of the application may set.X-Forwarded-For
setsREMOTE_ADDR
.X-Forwarded-Proto
setswsgi.url_scheme
.X-Forwarded-Host
setsHTTP_HOST
,SERVER_NAME
, andSERVER_PORT
.X-Forwarded-Port
setsHTTP_HOST
andSERVER_PORT
.X-Forwarded-Prefix
setsSCRIPT_NAME
.You must tell the middleware how many proxies set each header so itknows what values to trust. It is a security issue to trust valuesthat came from the client rather than a proxy.
The original values of the headers are stored in the WSGIenviron as werkzeug.proxy_fix.orig
, a dict.
Parameters:
- app – The WSGI application to wrap.
- x_for – Number of values to trust for
X-Forwarded-For
. - x_proto – Number of values to trust for
X-Forwarded-Proto
. - x_host – Number of values to trust for
X-Forwarded-Host
. - x_port – Number of values to trust for
X-Forwarded-Port
. - x_prefix – Number of values to trust for
X-Forwarded-Prefix
. - num_proxies – Deprecated, use
x_for
instead.
- from werkzeug.middleware.proxy_fix import ProxyFix
- # App is behind one proxy that sets the -For and -Host headers.
- app = ProxyFix(app, x_for=1, x_host=1)
Changed in version 0.15: All headers support multiple values. The num_proxies
argument is deprecated. Each header is configured with aseparate number of trusted proxies.
Changed in version 0.15: Original WSGI environ values are stored in thewerkzeug.proxy_fix.orig
dict. orig_remote_addr
,orig_wsgi_url_scheme
, and orig_http_host
are deprecatedand will be removed in 1.0.
Changed in version 0.15: Support X-Forwarded-Port
and X-Forwarded-Prefix
.
Changed in version 0.15: X-Fowarded-Host
and X-Forwarded-Port
modifySERVER_NAME
and SERVER_PORT
.