How to Configure Symfony to Work behind a Load Balancer or a Reverse Proxy¶

When you deploy your application, you may be behind a load balancer (e.g.
an AWS Elastic Load Balancing) or a reverse proxy (e.g. Varnish for
caching).

For the most part, this doesn't cause any problems with Symfony. But, when
a request passes through a proxy, certain request information is sent using
either the standard Forwarded header or non-standard special X-Forwarded-*
headers. For example, instead of reading the REMOTE_ADDR header (which
will now be the IP address of your reverse proxy), the user's true IP will be
stored in a standard Forwarded: for="..." header or a non standard
X-Forwarded-For header.

New in version 2.7: Forwarded header support was introduced in Symfony 2.7.

If you don't configure Symfony to look for these headers, you'll get incorrect
information about the client's IP address, whether or not the client is connecting
via HTTPS, the client's port and the hostname being requested.

In this example, you're saying that your reverse proxy (or proxies) has
the IP address 192.0.0.1 or matches the range of IP addresses that use
the CIDR notation 10.0.0.0/8. For more details, see the
framework.trusted_proxies option.

You are also saying that you trust that the proxy does not send conflicting
headers, e.g. sending both X-Forwarded-For and Forwarded in the same
request.

That's it! Symfony will now look for the correct headers to get information
like the client's IP address, host, port and whether the request is
using HTTPS.

Some reverse proxies (like AWS Elastic Load Balancing) don't have a
static IP address or even a range that you can target with the CIDR notation.
In this case, you'll need to - very carefully - trust all proxies.

Configure your web server(s) to not respond to traffic from any clients
other than your load balancers. For AWS, this can be done with security groups.

Once you've guaranteed that traffic will only come from your trusted reverse
proxies, configure Symfony to always trust incoming request. This is
done inside of your front controller:

Ensure that the trusted_proxies setting in your app/config/config.yml
is not set or it will overwrite the setTrustedProxies() call above.

That's it! It's critical that you prevent traffic from all non-trusted sources.
If you allow outside traffic, they could "spoof" their true IP address and
other information.

My Reverse Proxy Sends X-Forwarded-For but Does not Filter the Forwarded Header¶

Many popular proxy implementations do not yet support the Forwarded header
and do not filter it by default. Ideally, you would configure this in your
proxy. If this is not possible, you can tell Symfony to distrust the Forwarded
header, while still trusting your proxy's X-Forwarded-For header.