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 used 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, 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 (WSGIApplication) – The WSGI application to wrap.

  • x_for (int) – Number of values to trust for X-Forwarded-For.

  • x_proto (int) – Number of values to trust for X-Forwarded-Proto.

  • x_host (int) – Number of values to trust for X-Forwarded-Host.

  • x_port (int) – Number of values to trust for X-Forwarded-Port.

  • x_prefix (int) – Number of values to trust for X-Forwarded-Prefix.

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)
Changelog

Changed in version 1.0: The num_proxies argument and attribute; the get_remote_addr method; and the environ keys orig_remote_addr, orig_wsgi_url_scheme, and orig_http_host were removed.

Changed in version 0.15: All headers support multiple values. 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.

Changed in version 0.15: Support X-Forwarded-Port and X-Forwarded-Prefix.

Changed in version 0.15: X-Forwarded-Host and X-Forwarded-Port modify SERVER_NAME and SERVER_PORT.