PHPackages                             rossaddison/yii-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. rossaddison/yii-middleware

ActiveLibrary[Framework](/categories/framework)

rossaddison/yii-middleware
==========================

Yii Middleware

02.6kPHPCI failing

Since Mar 10Pushed 1y agoCompare

[ Source](https://github.com/rossaddison/yii-middleware)[ Packagist](https://packagist.org/packages/rossaddison/yii-middleware)[ RSS](/packages/rossaddison-yii-middleware/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (2)Used By (0)

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

Yii Middleware
==============

[](#yii-middleware)

[![Latest Stable Version](https://camo.githubusercontent.com/e569c63132202487250ce1382b6ae4dba2355975bf1679070b0f9eec1b8c8b08/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f7969692d6d6964646c65776172652f76)](https://packagist.org/packages/yiisoft/yii-middleware)[![Total Downloads](https://camo.githubusercontent.com/a596ea2f799493ff787ca7d12b447635b87800545668086000d7cb8595205825/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f7969692d6d6964646c65776172652f646f776e6c6f616473)](https://packagist.org/packages/yiisoft/yii-middleware)[![Build status](https://github.com/yiisoft/yii-middleware/actions/workflows/build.yml/badge.svg)](https://github.com/yiisoft/yii-middleware/actions/workflows/build.yml)[![Code Coverage](https://camo.githubusercontent.com/24f07199048aff5ad189068317bf05208b2eed6e64be91b0f5d4636a54c3c0fa/68747470733a2f2f636f6465636f762e696f2f67682f796969736f66742f7969692d6d6964646c65776172652f67726170682f62616467652e7376673f746f6b656e3d665a3453324c356b494a)](https://codecov.io/gh/yiisoft/yii-middleware)[![Mutation testing badge](https://camo.githubusercontent.com/2454a7e37b0ad9c16e340c21cde987b49ad0df4a8602f71f45ea8bb91fc7c4f0/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d253246796969736f66742532467969692d6d6964646c65776172652532466d6173746572)](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/yii-middleware/master)[![static analysis](https://github.com/yiisoft/yii-middleware/workflows/static%20analysis/badge.svg)](https://github.com/yiisoft/yii-middleware/actions?query=workflow%3A%22static+analysis%22)[![type-coverage](https://camo.githubusercontent.com/f08e7a8fe305fa38827d8f4b5a2a7998b2a7e607f8ddf8f24cb0071c5015bda8/68747470733a2f2f73686570686572642e6465762f6769746875622f796969736f66742f7969692d6d6964646c65776172652f636f7665726167652e737667)](https://shepherd.dev/github/yiisoft/yii-middleware)[![psalm-level](https://camo.githubusercontent.com/98ceee4422123a30db6c0ec3d8597a2626e444fc6eb08056b7e63e1b7212ce7e/68747470733a2f2f73686570686572642e6465762f6769746875622f796969736f66742f7969692d6d6964646c65776172652f6c6576656c2e737667)](https://shepherd.dev/github/yiisoft/yii-middleware)

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

- [`ForceSecureConnection`](#forcesecureconnection).
- [`HttpCache`](#httpcache).
- [`IpFilter`](#ipfilter).
- [`Redirect`](#redirect).
- [`Subfolder`](#subfolder).
- [`TagRequest`](#tagrequest).
- [`Locale`](#locale).
- [`CorsAllowAll`](#corsallowall).

For proxy related middleware, there is a separate package - [Yii Proxy Middleware](https://github.com/yiisoft/proxy-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/yii-middleware
```

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

[](#general-usage)

All classes are separate implementations of [PSR 15](https://github.com/php-fig/http-server-middleware)middleware and don't interact with each other in any way.

### `ForceSecureConnection`

[](#forcesecureconnection)

Redirects insecure requests from HTTP to HTTPS, and adds headers necessary to enhance the security policy.

```
use Yiisoft\Yii\Middleware\ForceSecureConnection;

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

$middleware = new ForceSecureConnection($responseFactory);

// Enables redirection from HTTP to HTTPS:
$middleware = $middleware->withRedirection(301);
// Disables redirection from HTTP to HTTPS:
$middleware = $middleware->withoutRedirection();

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

The `Content-Security-Policy` (CSP) header can force the browser to load page resources only through a secure connection, even if links in the page layout are specified with an unprotected protocol.

```
$middleware = $middleware->withCSP('upgrade-insecure-requests; default-src https:');
// Or without the `Content-Security-Policy` header in response:
$middleware = $middleware->withoutCSP();
```

Middleware adds HTTP Strict-Transport-Security (HSTS) header to each response. The header tells the browser that your site works with HTTPS only.

```
$maxAge = 3600; // Default is 31_536_000 (12 months).
$subDomains = false; // Whether to add the `includeSubDomains` option to the header value.

$middleware = $middleware->withHSTS($maxAge, $subDomains);
// Or without the `Strict-Transport-Security` header in response:
$middleware = $middleware->withoutHSTS();
```

### `HttpCache`

[](#httpcache)

Implements client-side caching by utilizing the `Last-Modified` and `ETag` HTTP headers.

```
use Yiisoft\Yii\Middleware\HttpCache;

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

$middleware = new HttpCache();

// Specify callable that generates the last modified:
$middleware = $middleware->withLastModified(function (ServerRequestInterface $request, mixed $params): int {
    $defaultLastModified = 3600;
    // Some actions.
    return $defaultLastModified;
});
// Specify callable that generates the ETag seed string:
$middleware = $middleware->withEtagSeed(function (ServerRequestInterface $request, mixed $params): string {
    $defaultEtagSeed = '33a64df551425fcc55e4d42a148795d9f25f89d4';
    // Some actions.
    return $defaultEtagSeed;
});

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

Additionally, you can specify the following options:

```
// Extra parameters for ETag seed string generation:
$middleware = $middleware->withParams(['parameter' => 'value']);

// The value of the `Cache-Control` HTTP header:
$middleware = $middleware->withCacheControlHeader('public, max-age=31536000');
// Default is `public, max-age=3600`. If null, the header won't be sent.

// Enable weak ETags generation (disabled by default):
$middleware = $middleware->withWeakTag();
// You should use weak ETags if the content is semantically equal, but not byte-equal.
```

### `IpFilter`

[](#ipfilter)

`IpFilter` allows access from specified IP ranges only and responds with 403 for all other IPs.

```
use Yiisoft\Yii\Middleware\IpFilter;

/**
 * @var Psr\Http\Message\ResponseFactoryInterface $responseFactory
 * @var Psr\Http\Message\ServerRequestInterface $request
 * @var Psr\Http\Server\RequestHandlerInterface $handler
 * @var Yiisoft\Validator\Rule\ValidatorInterface $validator
 */

// Name of the request attribute holding client IP:
$clientIpAttribute = 'client-ip';
// If there is no such attribute, or it has no value, then the middleware will respond with 403 forbidden.
// If the name of the request attribute is `null`, then `REMOTE_ADDR` server parameter is used to determine client IP.

$middleware = new IpFilter($validator, $responseFactory, $clientIpAttribute);

// Change client IP validator:
$middleware = $middleware->withValidator($validator);

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

### `Redirect`

[](#redirect)

Generates and adds a `Location` header to the response.

```
use Yiisoft\Yii\Middleware\Redirect;

/**
 * @var Psr\Http\Message\ResponseFactoryInterface $responseFactory
 * @var Psr\Http\Message\ServerRequestInterface $request
 * @var Psr\Http\Server\RequestHandlerInterface $handler
 * @var Yiisoft\Router\UrlGeneratorInterface $urlGenerator
 */

$middleware = new Redirect($ipValidator, $urlGenerator);

// Specify URL for redirection:
$middleware = $middleware->toUrl('/login');
// Or specify route data for redirection:
$middleware = $middleware->toRoute('auth/login', ['parameter' => 'value']);
// If you have set a redirect URL with "toUrl()" method, the middleware ignores the route data, since the URL is a
// priority.

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

You can also set the status of the response code for redirection.

```
// For permanent redirection (301):
$middleware = $middleware->permanent();

// For temporary redirection (302):
$middleware = $middleware->permanent();

// Or specify the status code yourself:
$middleware = $middleware->withStatus(303);
```

### `Subfolder`

[](#subfolder)

Supports routing when the entry point of the application isn't directly at the webroot. By default, it determines webroot based on server parameters.

> Info: You should place this middleware before `Route` middleware in the middleware list.

If you want the application to run on the specified path, use the prefix instead:

```
use Yiisoft\Yii\Middleware\Subfolder;

/**
 * @var Psr\Http\Message\ServerRequestInterface $request
 * @var Psr\Http\Server\RequestHandlerInterface $handler
 * @var Yiisoft\Aliases\Aliases $aliases
 * @var Yiisoft\Router\UrlGeneratorInterface $urlGenerator
 */

// URI prefix the specified immediately after the domain part (default is `null`):
$prefix = '/blog';
// The prefix value usually begins with a slash and must not end with a slash.

$middleware = new Subfolder($urlGenerator, $aliases, $prefix);

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

### `TagRequest`

[](#tagrequest)

Tags request with a random value that could be later used for identifying it.

```
use Yiisoft\Yii\Middleware\TagRequest;

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

$middleware = new TagRequest();
// In the process, a request attribute with the name `requestTag`
// and the generated value by the function `uniqid()` will be added.
$response = $middleware->process($request, $handler);
```

### `Locale`

[](#locale)

Supports locale-based routing and configures URL generator.

> Info: You should place this middleware before `Route` middleware in the middleware list.

```
use Yiisoft\Yii\Middleware\Locale;

// Available locales.
$locales = ['en' => 'en-US', 'ru' => 'ru-RU', 'uz' => 'uz-UZ']
/**
 * Specify supported locales.
 *
 * @var Locale $middleware
 */
$middleware = $middleware->withSupportedLocales($locales);

// Ignore requests which URLs that match "/api**" wildcard pattern.
$middleware = $middleware->withIgnoredRequestUrlPatterns(['/api**']);

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

The priority of lookup is the following:

1. URI query path, that's `/de/blog`.
2. URI query parameter name, that's `/blog?_language=de`. You can customize parameter name via `withQueryParameterName()`.
3. Cookie named `_language`. You can customize name via `withCookieName()`.
4. `Accept-Language` header. Not enabled by default. Use `withDetectLocale(true)` to enable it.

Found locale is not saved by default. It can be saved to cookies:

```
use Yiisoft\Yii\Middleware\Locale;

/** @var Locale $middleware */
$middleware = $middleware
    ->withCookieDuration(new DateInterval('P30D')) // Key parameter for activating saving to cookies.
    // Extra customization.
    ->withCookieName('_custom_name')
    ->withSecureCookie(true)
```

To configure more services, such as translator or session, use `SetLocaleEvent`([Yii Event Dispatcher](https://github.com/yiisoft/event-dispatcher) is required).

```
use Yiisoft\Translator\TranslatorInterface;
use Yiisoft\Yii\Middleware\Event\SetLocaleEvent;

final class SetLocaleEventHandler
{
    public function __construct(
        private TranslatorInterface $translator
    ) {
    }

    public function handle(SetLocaleEvent $event): void
    {
        $this->translator->setLocale($event->getLocale());
    }
}
```

> Note: Using tranlator requires [Yii Message Translator](https://github.com/yiisoft/translator).

### `CorsAllowAll`

[](#corsallowall)

Adds CORS headers to the response.

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

21

—

LowBetter than 19% of packages

Maintenance34

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity17

Early-stage or recently created project

 Bus Factor4

4 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/79f16141a5b619c098d6bec3812cd770dfc9b48eacc093f4ef88fbf20e735ec1?d=identicon)[yii2house2house](/maintainers/yii2house2house)

---

Top Contributors

[![arogachev](https://avatars.githubusercontent.com/u/8326201?v=4)](https://github.com/arogachev "arogachev (22 commits)")[![vjik](https://avatars.githubusercontent.com/u/525501?v=4)](https://github.com/vjik "vjik (18 commits)")[![rustamwin](https://avatars.githubusercontent.com/u/16498265?v=4)](https://github.com/rustamwin "rustamwin (12 commits)")[![xepozz](https://avatars.githubusercontent.com/u/6815714?v=4)](https://github.com/xepozz "xepozz (11 commits)")[![devanych](https://avatars.githubusercontent.com/u/20116244?v=4)](https://github.com/devanych "devanych (10 commits)")[![rossaddison](https://avatars.githubusercontent.com/u/8538339?v=4)](https://github.com/rossaddison "rossaddison (7 commits)")[![samdark](https://avatars.githubusercontent.com/u/47294?v=4)](https://github.com/samdark "samdark (7 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (6 commits)")[![luizcmarin](https://avatars.githubusercontent.com/u/67489841?v=4)](https://github.com/luizcmarin "luizcmarin (3 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (3 commits)")[![Arhell](https://avatars.githubusercontent.com/u/26163841?v=4)](https://github.com/Arhell "Arhell (2 commits)")[![terabytesoftw](https://avatars.githubusercontent.com/u/42547589?v=4)](https://github.com/terabytesoftw "terabytesoftw (2 commits)")[![sankaest](https://avatars.githubusercontent.com/u/21160342?v=4)](https://github.com/sankaest "sankaest (1 commits)")[![g-rodigy](https://avatars.githubusercontent.com/u/30372087?v=4)](https://github.com/g-rodigy "g-rodigy (1 commits)")[![bautrukevich](https://avatars.githubusercontent.com/u/1747220?v=4)](https://github.com/bautrukevich "bautrukevich (1 commits)")

### Embed Badge

![Health badge](/badges/rossaddison-yii-middleware/health.svg)

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

###  Alternatives

[laravel/telescope

An elegant debug assistant for the Laravel framework.

5.2k67.8M192](/packages/laravel-telescope)[spiral/roadrunner

RoadRunner: High-performance PHP application server and process manager written in Go and powered with plugins

8.4k12.2M84](/packages/spiral-roadrunner)[nolimits4web/swiper

Most modern mobile touch slider and framework with hardware accelerated transitions

41.8k177.2k1](/packages/nolimits4web-swiper)[laravel/dusk

Laravel Dusk provides simple end-to-end testing and browser automation.

1.9k36.7M257](/packages/laravel-dusk)[laravel/prompts

Add beautiful and user-friendly forms to your command-line applications.

708181.8M593](/packages/laravel-prompts)[cakephp/chronos

A simple API extension for DateTime.

1.4k47.7M121](/packages/cakephp-chronos)

PHPackages © 2026

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