X-Forwarded-For Proxy Fix

This module provides a middleware that adjusts the WSGI environ based on X-Forwarded- headers that proxies in front of an application may set.

When an application is running behind a proxy server, WSGI may see the request as coming from that server rather than the real client. Proxies set various headers to track where the request actually came from.

This middleware should only be applied if the application is actually behind such 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.

class werkzeug.middleware.proxy_fix.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 in front of the application may set.

  • X-Forwarded-For sets REMOTE_ADDR.
  • X-Forwarded-Proto sets wsgi.url_scheme.
  • X-Forwarded-Host sets HTTP_HOST, SERVER_NAME, and SERVER_PORT.
  • X-Forwarded-Port sets HTTP_HOST and SERVER_PORT.
  • X-Forwarded-Prefix sets SCRIPT_NAME.

You must tell the middleware how many proxies set each header so it knows what values to trust. It is a security issue to trust values that came from the client rather than a proxy.

The original values of the headers are stored in the WSGI environ 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 a separate number of trusted proxies.

Changed in version 0.15: Original WSGI environ values are stored in the werkzeug.proxy_fix.orig dict. orig_remote_addr, orig_wsgi_url_scheme, and orig_http_host are deprecated and 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 modify SERVER_NAME and SERVER_PORT.