<?php namespace app\middlewares; use Yii; use yii\base\BaseObject; use yii\base\InvalidArgumentException; use yii\web\Request; use yii\web\Response; use yii\web\UrlManager; class SeoMiddleware extends BaseObject implements yii\web\Middleware { public function processRequest(Request $request, $handler) { // Check if it's a static page request if ($this->isStaticPageRequest($request)) { // Parse the static page URL $url = $request->getUrl(); $parsedUrl = parse_url($url); $path = ltrim($parsedUrl['path'], '/'); // Get the controller and action method list($controller, $action) = explode('/', $path); // Build the new route $newRoute = $controller . '/' . $action; // Rewrite the request route $request->setPathInfo($newRoute); } // Continue processing the next middleware return $handler->handle($request); } // Check if it's a static page request protected function isStaticPageRequest(Request $request) { $url = $request->getUrl(); // Check if the URL matches the pattern for static pages return preg_match('/^\/[a-z-]+\/[a-z-]+$/i', $url); } }
'modules' => [ // ... ], 'components' => [ // ... ], 'middleware' => [ 'class' => 'app\middlewares\SeoMiddleware', ],
In the above configuration, we have added the SeoMiddleware class to the middleware component. This ensures that the middleware is called before the request reaches the controller.
To summarize, middleware is an ideal solution for implementing SEO and URL rewriting in the Yii framework. By creating a custom middleware class and registering it in the application configuration, we can easily implement these features. These functionalities improve the search engine friendliness of the website, enhance the user experience, and increase website traffic. Additionally, using middleware makes our code more modular and scalable. Therefore, when using Yii for web development, we should fully leverage middleware to achieve these optimizations.