{"id":14966361,"url":"https://github.com/yiisoft/yii-middleware","last_synced_at":"2026-03-16T20:33:11.426Z","repository":{"id":38028277,"uuid":"427322681","full_name":"yiisoft/yii-middleware","owner":"yiisoft","description":"Yii-specific middleware","archived":false,"fork":false,"pushed_at":"2024-09-09T07:10:46.000Z","size":219,"stargazers_count":21,"open_issues_count":10,"forks_count":8,"subscribers_count":21,"default_branch":"master","last_synced_at":"2024-10-29T14:35:38.146Z","etag":null,"topics":["hacktoberfest","middleware","psr-15","yii3"],"latest_commit_sha":null,"homepage":"https://www.yiiframework.com/","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yiisoft.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"open_collective":"yiisoft","github":["yiisoft"]}},"created_at":"2021-11-12T10:42:23.000Z","updated_at":"2024-10-07T17:32:54.000Z","dependencies_parsed_at":"2023-02-19T12:16:18.121Z","dependency_job_id":"c2945ffe-9809-4764-82e3-f83dcab8ac93","html_url":"https://github.com/yiisoft/yii-middleware","commit_stats":{"total_commits":97,"total_committers":15,"mean_commits":6.466666666666667,"dds":0.7731958762886598,"last_synced_commit":"198605591a9dcb37f433f232b022bc020f3ba43e"},"previous_names":[],"tags_count":5,"template":false,"template_full_name":"yiisoft/package-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Fyii-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Fyii-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Fyii-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Fyii-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yiisoft","download_url":"https://codeload.github.com/yiisoft/yii-middleware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241617891,"owners_count":19991767,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","middleware","psr-15","yii3"],"created_at":"2024-09-24T13:36:16.356Z","updated_at":"2026-03-16T20:33:11.421Z","avatar_url":"https://github.com/yiisoft.png","language":"PHP","funding_links":["https://opencollective.com/yiisoft","https://github.com/sponsors/yiisoft"],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/yiisoft\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://yiisoft.github.io/docs/images/yii_logo.svg\" height=\"100px\" alt=\"Yii\"\u003e\n    \u003c/a\u003e\n    \u003ch1 align=\"center\"\u003eYii Middleware\u003c/h1\u003e\n    \u003cbr\u003e\n\u003c/p\u003e\n\n[![Latest Stable Version](https://poser.pugx.org/yiisoft/yii-middleware/v)](https://packagist.org/packages/yiisoft/yii-middleware)\n[![Total Downloads](https://poser.pugx.org/yiisoft/yii-middleware/downloads)](https://packagist.org/packages/yiisoft/yii-middleware)\n[![Build status](https://github.com/yiisoft/yii-middleware/actions/workflows/build.yml/badge.svg)](https://github.com/yiisoft/yii-middleware/actions/workflows/build.yml)\n[![Code Coverage](https://codecov.io/gh/yiisoft/yii-middleware/graph/badge.svg?token=fZ4S2L5kIJ)](https://codecov.io/gh/yiisoft/yii-middleware)\n[![Mutation testing badge](https://img.shields.io/endpoint?style=flat\u0026url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fyiisoft%2Fyii-middleware%2Fmaster)](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/yii-middleware/master)\n[![Static analysis](https://github.com/yiisoft/yii-middleware/actions/workflows/static.yml/badge.svg?branch=master)](https://github.com/yiisoft/yii-middleware/actions/workflows/static.yml?query=branch%3Amaster)\n[![type-coverage](https://shepherd.dev/github/yiisoft/yii-middleware/coverage.svg)](https://shepherd.dev/github/yiisoft/yii-middleware)\n[![psalm-level](https://shepherd.dev/github/yiisoft/yii-middleware/level.svg)](https://shepherd.dev/github/yiisoft/yii-middleware)\n\nThe package provides middleware classes that implement [PSR-15](https://www.php-fig.org/psr/psr-15/#12-middleware):\n\n- [`ForceSecureConnection`](#forcesecureconnection).\n- [`HttpCache`](#httpcache).\n- [`IpFilter`](#ipfilter).\n- [`Redirect`](#redirect).\n- [`Subfolder`](#subfolder).\n- [`TagRequest`](#tagrequest).\n- [`Locale`](#locale).\n- [`CorsAllowAll`](#corsallowall).\n\nFor proxy related middleware, there is a separate package -\n[Yii Proxy Middleware](https://github.com/yiisoft/proxy-middleware).\n\nFor more information on how to use middleware in the [Yii Framework](https://www.yiiframework.com/), see the\n[Yii middleware guide](https://github.com/yiisoft/docs/blob/master/guide/en/structure/middleware.md).\n\n## Requirements\n\n- PHP 8.1 - 8.5.\n\n## Installation\n\nThe package could be installed with [Composer](https://getcomposer.org):\n\n```shell\ncomposer require yiisoft/yii-middleware\n```\n\n## General usage\n\nAll classes are separate implementations of [PSR 15](https://github.com/php-fig/http-server-middleware)\nmiddleware and don't interact with each other in any way.\n\n### `ForceSecureConnection`\n\nRedirects insecure requests from HTTP to HTTPS, and adds headers necessary to enhance the security policy.\n\n```php\nuse Yiisoft\\Yii\\Middleware\\ForceSecureConnection;\n\n/**\n * @var Psr\\Http\\Message\\ResponseFactoryInterface $responseFactory\n * @var Psr\\Http\\Message\\ServerRequestInterface $request\n * @var Psr\\Http\\Server\\RequestHandlerInterface $handler\n */\n\n$middleware = new ForceSecureConnection($responseFactory);\n\n// Enables redirection from HTTP to HTTPS:\n$middleware = $middleware-\u003ewithRedirection(301);\n// Disables redirection from HTTP to HTTPS:\n$middleware = $middleware-\u003ewithoutRedirection();\n\n$response = $middleware-\u003eprocess($request, $handler);\n```\n\nThe `Content-Security-Policy` (CSP) header can force the browser to load page resources only through\na secure connection, even if links in the page layout are specified with an unprotected protocol.\n\n```php\n$middleware = $middleware-\u003ewithCSP('upgrade-insecure-requests; default-src https:');\n// Or without the `Content-Security-Policy` header in response:\n$middleware = $middleware-\u003ewithoutCSP();\n```\n\nMiddleware adds HTTP Strict-Transport-Security (HSTS) header to each response.\nThe header tells the browser that your site works with HTTPS only.\n\n```php\n$maxAge = 3600; // Default is 31_536_000 (12 months).\n$subDomains = false; // Whether to add the `includeSubDomains` option to the header value.\n\n$middleware = $middleware-\u003ewithHSTS($maxAge, $subDomains);\n// Or without the `Strict-Transport-Security` header in response:\n$middleware = $middleware-\u003ewithoutHSTS();\n```\n\n### `HttpCache`\n\nImplements client-side caching by utilizing the `Last-Modified` and `ETag` HTTP headers.\n\n```php\nuse Yiisoft\\Yii\\Middleware\\HttpCache;\n\n/**\n * @var Psr\\Http\\Message\\ServerRequestInterface $request\n * @var Psr\\Http\\Server\\RequestHandlerInterface $handler\n */\n\n$middleware = new HttpCache();\n\n// Specify callable that generates the last modified:\n$middleware = $middleware-\u003ewithLastModified(function (ServerRequestInterface $request, mixed $params): int {\n    $defaultLastModified = 3600;\n    // Some actions.\n    return $defaultLastModified;\n});\n// Specify callable that generates the ETag seed string:\n$middleware = $middleware-\u003ewithEtagSeed(function (ServerRequestInterface $request, mixed $params): string {\n    $defaultEtagSeed = '33a64df551425fcc55e4d42a148795d9f25f89d4';\n    // Some actions.\n    return $defaultEtagSeed;\n});\n\n$response = $middleware-\u003eprocess($request, $handler);\n```\n\nAdditionally, you can specify the following options:\n\n```php\n// Extra parameters for ETag seed string generation:\n$middleware = $middleware-\u003ewithParams(['parameter' =\u003e 'value']);\n\n// The value of the `Cache-Control` HTTP header:\n$middleware = $middleware-\u003ewithCacheControlHeader('public, max-age=31536000');\n// Default is `public, max-age=3600`. If null, the header won't be sent.\n\n// Enable weak ETags generation (disabled by default):\n$middleware = $middleware-\u003ewithWeakTag();\n// You should use weak ETags if the content is semantically equal, but not byte-equal.\n```\n\n### `IpFilter`\n\n`IpFilter` allows access from specified IP ranges only and responds with 403 for all other IPs.\n\n```php\nuse Yiisoft\\Yii\\Middleware\\IpFilter;\n\n/**\n * @var Psr\\Http\\Message\\ResponseFactoryInterface $responseFactory\n * @var Psr\\Http\\Message\\ServerRequestInterface $request\n * @var Psr\\Http\\Server\\RequestHandlerInterface $handler\n * @var Yiisoft\\Validator\\Rule\\ValidatorInterface $validator\n */\n\n// Name of the request attribute holding client IP:\n$clientIpAttribute = 'client-ip';\n// If there is no such attribute, or it has no value, then the middleware will respond with 403 forbidden.\n// If the name of the request attribute is `null`, then `REMOTE_ADDR` server parameter is used to determine client IP.\n\n$middleware = new IpFilter($validator, $responseFactory, $clientIpAttribute);\n\n// Change client IP validator:\n$middleware = $middleware-\u003ewithValidator($validator);\n\n$response = $middleware-\u003eprocess($request, $handler);\n```\n\n### `Redirect`\n\nGenerates and adds a `Location` header to the response.\n\n```php\nuse Yiisoft\\Yii\\Middleware\\Redirect;\n\n/**\n * @var Psr\\Http\\Message\\ResponseFactoryInterface $responseFactory\n * @var Psr\\Http\\Message\\ServerRequestInterface $request\n * @var Psr\\Http\\Server\\RequestHandlerInterface $handler\n * @var Yiisoft\\Router\\UrlGeneratorInterface $urlGenerator\n */\n\n$middleware = new Redirect($ipValidator, $urlGenerator);\n\n// Specify URL for redirection:\n$middleware = $middleware-\u003etoUrl('/login');\n// Or specify route data for redirection:\n$middleware = $middleware-\u003etoRoute('auth/login', ['parameter' =\u003e 'value']);\n// If you have set a redirect URL with \"toUrl()\" method, the middleware ignores the route data, since the URL is a\n// priority.\n\n$response = $middleware-\u003eprocess($request, $handler);\n```\n\nYou can also set the status of the response code for redirection.\n\n```php\n// For permanent redirection (301):\n$middleware = $middleware-\u003epermanent();\n\n// For temporary redirection (302):\n$middleware = $middleware-\u003epermanent();\n\n// Or specify the status code yourself:\n$middleware = $middleware-\u003ewithStatus(303);\n```\n\n### `Subfolder`\n\nSupports routing when the entry point of the application isn't directly at the webroot.\nBy default, it determines webroot based on server parameters.\n\n\u003e Info: You should place this middleware before `Route` middleware in the middleware list.\n\nIf you want the application to run on the specified path, use the prefix instead:\n\n```php\nuse Yiisoft\\Yii\\Middleware\\Subfolder;\n\n/**\n * @var Psr\\Http\\Message\\ServerRequestInterface $request\n * @var Psr\\Http\\Server\\RequestHandlerInterface $handler\n * @var Yiisoft\\Aliases\\Aliases $aliases\n * @var Yiisoft\\Router\\UrlGeneratorInterface $urlGenerator\n */\n \n// URI prefix the specified immediately after the domain part (default is `null`):\n$prefix = '/blog';\n// The prefix value usually begins with a slash and must not end with a slash.\n\n$middleware = new Subfolder($urlGenerator, $aliases, $prefix);\n\n$response = $middleware-\u003eprocess($request, $handler);\n```\n\n### `TagRequest`\n\nTags request with a random value that could be later used for identifying it.\n\n```php\nuse Yiisoft\\Yii\\Middleware\\TagRequest;\n\n/**\n * @var Psr\\Http\\Message\\ServerRequestInterface $request\n * @var Psr\\Http\\Server\\RequestHandlerInterface $handler\n */\n\n$middleware = new TagRequest();\n// In the process, a request attribute with the name `requestTag`\n// and the generated value by the function `uniqid()` will be added.\n$response = $middleware-\u003eprocess($request, $handler);\n```\n\n### `Locale`\n\nSupports locale-based routing and configures URL generator.\n\n\u003e Info: You should place this middleware before `Route` middleware in the middleware list.\n\n```php\nuse Yiisoft\\Yii\\Middleware\\Locale;\n\n// Available locales.\n$locales = ['en' =\u003e 'en-US', 'ru' =\u003e 'ru-RU', 'uz' =\u003e 'uz-UZ']\n/**\n * Specify supported locales.\n * \n * @var Locale $middleware\n */\n$middleware = $middleware-\u003ewithSupportedLocales($locales);\n\n// Ignore requests which URLs that match \"/api**\" wildcard pattern.\n$middleware = $middleware-\u003ewithIgnoredRequestUrlPatterns(['/api**']);\n\n$response = $middleware-\u003eprocess($request);\n```\n\nThe priority of lookup is the following:\n\n1. URI query path, that's `/de/blog`.\n2. URI query parameter name, that's `/blog?_language=de`.\n   You can customize parameter name via `withQueryParameterName()`.\n3. Cookie named `_language`. You can customize name via `withCookieName()`.\n4. `Accept-Language` header. Not enabled by default. Use `withDetectLocale(true)` to enable it.\n\nFound locale is not saved by default. It can be saved to cookies:\n\n```php\nuse Yiisoft\\Yii\\Middleware\\Locale;\n\n/** @var Locale $middleware */\n$middleware = $middleware\n    -\u003ewithCookieDuration(new DateInterval('P30D')) // Key parameter for activating saving to cookies.\n    // Extra customization.\n    -\u003ewithCookieName('_custom_name')\n    -\u003ewithSecureCookie(true)\n```\n\nTo configure more services, such as translator or session, use `SetLocaleEvent`\n([Yii Event Dispatcher](https://github.com/yiisoft/event-dispatcher) is required).\n\n```php\nuse Yiisoft\\Translator\\TranslatorInterface;\nuse Yiisoft\\Yii\\Middleware\\Event\\SetLocaleEvent;\n\nfinal class SetLocaleEventHandler\n{\n    public function __construct(\n        private TranslatorInterface $translator\n    ) {\n    }\n\n    public function handle(SetLocaleEvent $event): void\n    {\n        $this-\u003etranslator-\u003esetLocale($event-\u003egetLocale());\n    }\n}\n```\n\n\u003e Note: Using tranlator requires [Yii Message Translator](https://github.com/yiisoft/translator).\n\n### `CorsAllowAll`\n\nAdds CORS headers to the response.\n\n## Documentation\n\n- [Internals](docs/internals.md)\n\nIf 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.\nYou may also check out other [Yii Community Resources](https://www.yiiframework.com/community).\n\n## License\n\nThe Yii Middleware is free software. It is released under the terms of the BSD License.\nPlease see [`LICENSE`](./LICENSE.md) for more information.\n\nMaintained by [Yii Software](https://www.yiiframework.com/).\n\n## Support the project\n\n[![Open Collective](https://img.shields.io/badge/Open%20Collective-sponsor-7eadf1?logo=open%20collective\u0026logoColor=7eadf1\u0026labelColor=555555)](https://opencollective.com/yiisoft)\n\n## Follow updates\n\n[![Official website](https://img.shields.io/badge/Powered_by-Yii_Framework-green.svg?style=flat)](https://www.yiiframework.com/)\n[![Twitter](https://img.shields.io/badge/twitter-follow-1DA1F2?logo=twitter\u0026logoColor=1DA1F2\u0026labelColor=555555?style=flat)](https://twitter.com/yiiframework)\n[![Telegram](https://img.shields.io/badge/telegram-join-1DA1F2?style=flat\u0026logo=telegram)](https://t.me/yii3en)\n[![Facebook](https://img.shields.io/badge/facebook-join-1DA1F2?style=flat\u0026logo=facebook\u0026logoColor=ffffff)](https://www.facebook.com/groups/yiitalk)\n[![Slack](https://img.shields.io/badge/slack-join-1DA1F2?style=flat\u0026logo=slack)](https://yiiframework.com/go/slack)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyiisoft%2Fyii-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyiisoft%2Fyii-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyiisoft%2Fyii-middleware/lists"}