|
| 1 | +.. index:: |
| 2 | + single: Request; Trusted Proxies |
| 3 | + |
| 4 | +Trusting Proxies |
| 5 | +================ |
| 6 | + |
| 7 | +If you find yourself behind some sort of proxy - like a load balancer - then |
| 8 | +certain header information may be sent to you using special ``X-Forwarded-*`` |
| 9 | +headers. For example, the ``Host`` HTTP header is usually used to return |
| 10 | +the requested host. But when you're behind a proxy, the true host may be |
| 11 | +stored in a ``X-Forwarded-Host`` header. |
| 12 | + |
| 13 | +Since HTTP headers can be spoofed, Symfony2 does *not* trust these proxy |
| 14 | +headers by default. If you are behind a proxy, you should manually whitelist |
| 15 | +your proxy:: |
| 16 | + |
| 17 | + use Symfony\Component\HttpFoundation\Request; |
| 18 | + |
| 19 | + $request = Request::createFromGlobals(); |
| 20 | + // only trust proxy headers coming from this IP address |
| 21 | + $request->setTrustedProxies(array(192.0.0.1)); |
| 22 | + |
| 23 | +Configuring Header Names |
| 24 | +------------------------ |
| 25 | + |
| 26 | +By default, the following proxy headers are trusted: |
| 27 | + |
| 28 | +* ``X-Forwarded-For`` Used in :method:`Symfony\\Component\\HttpFoundation\\Request::getClientIp`; |
| 29 | +* ``X-Forwarded-Host`` Used in :method:`Symfony\\Component\\HttpFoundation\\Request::getHost`; |
| 30 | +* ``X-Forwarded-Port`` Used in :method:`Symfony\\Component\\HttpFoundation\\Request::getPort`; |
| 31 | +* ``X-Forwarded-Proto`` Used in :method:`Symfony\\Component\\HttpFoundation\\Request::getScheme` and :method:`Symfony\\Component\\HttpFoundation\\Request::isSecure`; |
| 32 | + |
| 33 | +If your reverse proxy uses a different header name for any of these, you |
| 34 | +can configure that header name via :method:`Symfony\\Component\\HttpFoundation\\Request::setTrustedHeaderName`:: |
| 35 | + |
| 36 | + $request->setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X-Proxy-For'); |
| 37 | + $request->setTrustedHeaderName(Request::HEADER_CLIENT_HOST, 'X-Proxy-Host'); |
| 38 | + $request->setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X-Proxy-Port'); |
| 39 | + $request->setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X-Proxy-Proto'); |
| 40 | + |
| 41 | +Not trusting certain Headers |
| 42 | +---------------------------- |
| 43 | + |
| 44 | +By default, if you whitelist your proxy's IP address, then all four headers |
| 45 | +listed above are trusted. If you need to trust some of these headers but |
| 46 | +not others, you can do that as well:: |
| 47 | + |
| 48 | + // disables trusting the ``X-Forwarded-Proto`` header, the default header is used |
| 49 | + $request->setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, ''); |
0 commit comments