PHPackages                             yiisoft/proxy-middleware - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. yiisoft/proxy-middleware

ActiveLibrary[Framework](/categories/framework)

yiisoft/proxy-middleware
========================

Yii Proxy Middleware

1.0.2(1y ago)71.6k↓33.3%2[4 issues](https://github.com/yiisoft/proxy-middleware/issues)[1 PRs](https://github.com/yiisoft/proxy-middleware/pulls)1BSD-3-ClausePHPPHP ^8.0CI passing

Since Jun 30Pushed 1w ago12 watchersCompare

[ Source](https://github.com/yiisoft/proxy-middleware)[ Packagist](https://packagist.org/packages/yiisoft/proxy-middleware)[ Docs](https://www.yiiframework.com/)[ GitHub Sponsors](https://github.com/sponsors/yiisoft)[ OpenCollective](https://opencollective.com/yiisoft)[ RSS](/packages/yiisoft-proxy-middleware/feed)WikiDiscussions master Synced yesterday

READMEChangelog (3)Dependencies (13)Versions (7)Used By (1)

 [ ![Yii](https://camo.githubusercontent.com/8317c17418b39410a660f5149071d26c5023c0d5fb2b7ebb771324812f666d73/68747470733a2f2f796969736f66742e6769746875622e696f2f646f63732f696d616765732f7969695f6c6f676f2e737667) ](https://github.com/yiisoft)

Yii Proxy Middleware
====================

[](#yii-proxy-middleware)

[![Latest Stable Version](https://camo.githubusercontent.com/30c30eeffc8f0a22b313f6fe77e268b95b275fd9d470047d52636c3b1447d0be/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f70726f78792d6d6964646c65776172652f76)](https://packagist.org/packages/yiisoft/proxy-middleware)[![Total Downloads](https://camo.githubusercontent.com/3a13622d1f9319f14b2ca967f5e5d9531d2ab4611869388f6fc6063446661d7d/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f70726f78792d6d6964646c65776172652f646f776e6c6f616473)](https://packagist.org/packages/yiisoft/proxy-middleware)[![Build status](https://github.com/yiisoft/proxy-middleware/actions/workflows/build.yml/badge.svg)](https://github.com/yiisoft/proxy-middleware/actions/workflows/build.yml)[![Code Coverage](https://camo.githubusercontent.com/559f8b17f1fd82b5c5fa21f5a8e3a52e77dc1c8d4157014bb587802a845ab9d8/68747470733a2f2f636f6465636f762e696f2f67682f796969736f66742f70726f78792d6d6964646c65776172652f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/yiisoft/proxy-middleware)[![Mutation testing badge](https://camo.githubusercontent.com/6bd13f1351fd9c04cc5c0e60f14d566365ff18bb310bd303e0e70d0279d048ca/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d253246796969736f667425324670726f78792d6d6964646c65776172652532466d6173746572)](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/proxy-middleware/master)[![static analysis](https://github.com/yiisoft/proxy-middleware/workflows/static%20analysis/badge.svg)](https://github.com/yiisoft/proxy-middleware/actions?query=workflow%3A%22static+analysis%22)[![type-coverage](https://camo.githubusercontent.com/0b99ca6a3ad1887cf8133b87a2313210c4a275412f5609e689fb4b510487683d/68747470733a2f2f73686570686572642e6465762f6769746875622f796969736f66742f70726f78792d6d6964646c65776172652f636f7665726167652e737667)](https://shepherd.dev/github/yiisoft/proxy-middleware)[![psalm-level](https://camo.githubusercontent.com/7c718ecbfb2194bc9a39d7533aec045aba39ed23e721ec94b992766e3537a551/68747470733a2f2f73686570686572642e6465762f6769746875622f796969736f66742f70726f78792d6d6964646c65776172652f6c6576656c2e737667)](https://shepherd.dev/github/yiisoft/proxy-middleware)

The package provides proxy related middleware classes that implement [PSR-15](https://www.php-fig.org/psr/psr-15/#12-middleware):

- [`TrustedHeaderProtocolResolver`](#trustedheaderprotocolresolver).
- [`TrustedHostsNetworkResolver`](#trustedhostsnetworkresolver).

For other miscellaneous middleware, there is a separate package - [Yii Middleware](https://github.com/yiisoft/yii-middleware).

For more information on how to use middleware in the [Yii Framework](https://www.yiiframework.com/), see the [Yii middleware guide](https://github.com/yiisoft/docs/blob/master/guide/en/structure/middleware.md).

Requirements
------------

[](#requirements)

- PHP 8.0 or higher.

Installation
------------

[](#installation)

The package could be installed with [Composer](https://getcomposer.org):

```
composer require yiisoft/proxy-middleware
```

General usage
-------------

[](#general-usage)

### `TrustedHeaderProtocolResolver`

[](#trustedheaderprotocolresolver)

Trusted header protocol resolver sets a server request protocol based on special header you trust such as `X-Forwarded-Proto`.

You can use it if your server is behind a trusted load balancer or a proxy that's always setting the special header itself discarding any header values provided by user.

```
use Yiisoft\Yii\Middleware\TrustedHeaderProtocolResolver;

/**
 * @var Psr\Http\Message\ServerRequestInterface $request
 * @var Psr\Http\Server\RequestHandlerInterface $handler
 */

$middleware = new TrustedHeaderProtocolResolver();

$middleware = $middleware->withAddedProtocolHeader('x-forwarded-proto', [
    'http' => ['http'],
    'https' => ['https', 'on'],
]);
// Disable earlier settings:
$middleware = $middleware->withoutProtocolHeader('x-forwarded-proto');

$response = $middleware->process($request, $handler);
```

### `TrustedHostsNetworkResolver`

[](#trustedhostsnetworkresolver)

Scans the entire connection chain and resolves the data from forwarded headers taking into account trusted IPs. Additionally, all items' structure is thoroughly validated because headers' data can't be trusted. The following data is resolved:

- IP.
- Protocol
- Host.
- Port.
- IP identifier - [unknown](https://datatracker.ietf.org/doc/html/rfc7239#section-6.2) or [obfuscated](https://datatracker.ietf.org/doc/html/rfc7239#section-6.3). Used with `Forwarded` RFC header.

The typical use case is having an application behind a load balancer.

#### Trusted IPs

[](#trusted-ips)

A list of trusted IPs from connection chain.

Proxies' IPs including the one in `$_SERVER['REMOTE_ADDR']` must be specified here. For example, for `$_SERVER['REMOTE_ADDR']` with value `18.18.18.18` and 2 other proxies - `2.2.2.2` and `8.8.8.8`, the configuration will be:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withTrustedIps([['8.8.8.8', '2.2.2.2', '18.18.18.18']]);
```

The order of IPs is not important.

#### Forwarded header groups

[](#forwarded-header-groups)

Header groups to parse the data from. By including headers in this list, they are trusted automatically.

The default is:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,
]);
```

which is an alternative/shorter way of writing this:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    'forwarded',
    [
        'ip' => 'x-forwarded-for',
        'protocol' => 'x-forwarded-proto',
        'host' => 'x-forwarded-host',
        'port' => 'x-forwarded-port',
    ],
]);
```

The accepted values are:

- `TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC` string constant. Parse all data from single `Forwarded`header according to [RFC 7239](https://datatracker.ietf.org/doc/html/rfc7239).
- Array. Parse data from separate forwarded headers with "X" prefix. Unlike with RFC variation, each header stores only one data unit (for example, IP). Headers with "X" prefix are quite common despite being non-standard:
    - [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For) - IP.
    - [X-Forwarded-Proto](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto) - protocol.
    - [X-Forwarded-Host](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Host) - host.
    - `X-Forwarded-Port` - port.

The header groups are processed in the order they are defined. If the header containing IP is present and is non-empty, this group will be selected and further ones will be ignored.

You can add support for custom headers and/or change priority:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    [
        'ip' => 'y-forwarded-for',
        'protocol' => 'y-forwarded-proto',
        'host' => 'y-forwarded-host',
        'port' => 'y-forwarded-port',
    ],
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,
]);
```

For protocol, it's also possible to resolve non-standard values via mapping:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,
    [
        'ip' => 'y-forwarded-for',
        'protocol' => [
            'front-end-https',
            ['on' => 'https'],
        ],
        'host' => 'y-forwarded-host',
        'port' => 'y-forwarded-port',
    ],
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,
]);
```

or via callable:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,
    [
        'ip' => 'y-forwarded-for',
        'protocol' => [
            'front-end-https',
            static fn (string $protocol): ?string => $protocol === 'On' ? 'https': 'http',,
        ],
        'host' => 'y-forwarded-host',
        'port' => 'y-forwarded-port',
    ],
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,
]);
```

It's also a good idea to limit default header groups to the only guaranteed sources of data:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,
]);
```

#### Typical forwarded headers

[](#typical-forwarded-headers)

List of headers that are considered related to forwarding.

The default is:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withTypicalForwardedHeaders([
    // RFC
    'forwarded',

    // "X" prefix
    'x-forwarded-for',
    'x-forwarded-host',
    'x-forwarded-proto',
    'x-forwarded-port',

    // Microsoft
    'front-end-https',
]);
```

The headers that are present in this list but missing in a matching forwarded header group will be deleted from request because they are potentially not secure and likely were not passed by a proxy server.

For example, with default forwarded header groups' setup used as well:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withForwardedHeaderGroups([
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_RFC,
    TrustedHostsNetworkResolver::FORWARDED_HEADER_GROUP_X_PREFIX,
]);
```

and with the following request headers passed:

```
[
    'Forwarded' => [
        'for="9.9.9.9:8013";proto=http;host=example13.com',
        'for="8.8.8.8:8012";proto=http;host=example12.com',
        'for="2.2.2.2:8011";proto=http;host=example11.com',
    ],
    'X-Forwarded-For' => 'not-secure',
    'X-Forwarded-Host' => 'not-secure',
    'X-Forwarded-Proto' => 'not-secure',
    'X-Forwarded-Port' => 'not-secure',
    'Front-End-Https' => 'not-secure',
    'Non-Forwarded' => 'not-typical',
];
```

middleware will remove these headers from request:

- `x-forwarded-for`.
- `x-forwarded-host`.
- `x-forwarded-proto`.
- `x-forwarded-port`.
- `front-end-https`.

because RFC group is matching and the rest can't be trusted. The headers that are not declared as typical forwarded headers will be left as is (`Non-Forwarded` in the example above).

#### Accessing resolved data

[](#accessing-resolved-data)

Resolved IP is saved to a special request's attribute:

```
use Psr\Http\Message\ServerRequestInterface;

/** @var ServerRequestInterface $request */
$ip = $request->getAttribute(TrustedHostsNetworkResolver::ATTRIBUTE_REQUEST_CLIENT_IP);
```

There is an additional attribute allowing to retrieve all previous validated and trusted connection chain items. It needs explicit configuration:

```
use Psr\Http\Message\ServerRequestInterface;
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

/** @var TrustedHostsNetworkResolver $middleware */
$middleware = $middleware->withConnectionChainItemsAttribute('connectionChainItems');
// ...
/** @var ServerRequestInterface $request */
$connectionChainItems = $request->getAttribute('connectionChainItems');
```

An example of contents:

```
[
    [
        'ip' => '18.18.18.18',
        'protocol' => null,
        'host' => null,
        'port' => null,
        'ipIdentifier' => null,
    ],
    [
        'ip' => '2.2.2.2',
        'protocol' => 'http',
        'host' => 'example1.com',
        'port' => null,
        'ipIdentifier' => '_obfuscated1',
    ]
],
```

#### Reverse-obfuscating IP identifier

[](#reverse-obfuscating-ip-identifier)

You may extend middleware class and provide reverse-obfuscating logic for [obfuscated](https://datatracker.ietf.org/doc/html/rfc7239#section-6.3) IP identifiers:

```
use Yiisoft\ProxyMiddleware\TrustedHostsNetworkResolver;

class MyTrustedHostsNetworkResolver extends TrustedHostsNetworkResolver
{
    protected function reverseObfuscateIpIdentifier(
        string $ipIdentifier,
        array $validatedConnectionChainItems,
        array $remainingConnectionChainItems,
        RequestInterface $request,
    ): ?array
    {
        return match ($ipIdentifier) {
            '_obfuscated1' => ['2.2.2.2', null], // Without port
            '_obfuscated2' => ['5.5.5.5', '8082'], // With port
            default => null, // Unable to resolve (default)
        };
    }
}
```

Documentation
-------------

[](#documentation)

- [Internals](docs/internals.md)

If you need help or have a question, the [Yii Forum](https://forum.yiiframework.com/c/yii-3-0/63) is a good place for that. You may also check out other [Yii Community Resources](https://www.yiiframework.com/community).

License
-------

[](#license)

The Yii Proxy Middleware is free software. It is released under the terms of the BSD License. Please see [`LICENSE`](./LICENSE.md) for more information.

Maintained by [Yii Software](https://www.yiiframework.com/).

Support the project
-------------------

[](#support-the-project)

[![Open Collective](https://camo.githubusercontent.com/a2b15f8e2268d4e3842e00d41ff7a57cce2ad8bd8d8769c5dc4fa05a546a4f62/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4f70656e253230436f6c6c6563746976652d73706f6e736f722d3765616466313f6c6f676f3d6f70656e253230636f6c6c656374697665266c6f676f436f6c6f723d376561646631266c6162656c436f6c6f723d353535353535)](https://opencollective.com/yiisoft)

Follow updates
--------------

[](#follow-updates)

[![Official website](https://camo.githubusercontent.com/d6b0929173e28cc627430d2519ca1853466a70f37395877eaf4820cb3e1e1909/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f506f77657265645f62792d5969695f4672616d65776f726b2d677265656e2e7376673f7374796c653d666c6174)](https://www.yiiframework.com/)[![Twitter](https://camo.githubusercontent.com/d077c362ac639792171af8bc002ee827816733dfc0925f70b557e6d151022226/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f747769747465722d666f6c6c6f772d3144413146323f6c6f676f3d74776974746572266c6f676f436f6c6f723d314441314632266c6162656c436f6c6f723d3535353535353f7374796c653d666c6174)](https://twitter.com/yiiframework)[![Telegram](https://camo.githubusercontent.com/4e38dd12535575c39c65bea7119b95e663abb2d1f4e3d669a27bbda07ef603f0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74656c656772616d2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d74656c656772616d)](https://t.me/yii3en)[![Facebook](https://camo.githubusercontent.com/48204e301b34b29b0815854544f04c337fc0692096cab35e9a1f8c53a42c2307/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f66616365626f6f6b2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d66616365626f6f6b266c6f676f436f6c6f723d666666666666)](https://www.facebook.com/groups/yiitalk)[![Slack](https://camo.githubusercontent.com/1a3645ba1c97e6684d0349bc478201e1621ba0d3efad516d81035364d442bad7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f736c61636b2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d736c61636b)](https://yiiframework.com/go/slack)

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance58

Moderate activity, may be stable

Popularity26

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~201 days

Total

3

Last Release

696d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/fc29e4e7068a00fe9b9db37b8aadda1db6020adcacef810461e47b99c2b150e6?d=identicon)[samdark](/maintainers/samdark)

![](https://www.gravatar.com/avatar/53e5ee1dedd50f71e4aeeac2929f786cdfb400359d4776e6cd806388d0d5df2c?d=identicon)[vjik](/maintainers/vjik)

---

Top Contributors

[![vjik](https://avatars.githubusercontent.com/u/525501?v=4)](https://github.com/vjik "vjik (12 commits)")[![arogachev](https://avatars.githubusercontent.com/u/8326201?v=4)](https://github.com/arogachev "arogachev (10 commits)")[![luizcmarin](https://avatars.githubusercontent.com/u/67489841?v=4)](https://github.com/luizcmarin "luizcmarin (2 commits)")[![samdark](https://avatars.githubusercontent.com/u/47294?v=4)](https://github.com/samdark "samdark (1 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (1 commits)")

---

Tags

forwardedload-balancermiddlewareproxypsr-15yii3middlewareframeworkyii

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm, Rector

Type Coverage Yes

### Embed Badge

![Health badge](/badges/yiisoft-proxy-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/yiisoft-proxy-middleware/health.svg)](https://phpackages.com/packages/yiisoft-proxy-middleware)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.9k19.5M1.8k](/packages/cakephp-cakephp)[cakephp/authentication

Authentication plugin for CakePHP

1214.1M106](/packages/cakephp-authentication)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[yiisoft/yii-middleware

Yii Middleware

21164.1k1](/packages/yiisoft-yii-middleware)[typo3/cms-core

TYPO3 CMS Core

3713.2M5.1k](/packages/typo3-cms-core)[windwalker/framework

The next generation PHP framework.

25740.3k1](/packages/windwalker-framework)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
