Current Location: Home> Latest Articles> Yii Framework Middleware: How to Implement SEO and URL Rewriting

Yii Framework Middleware: How to Implement SEO and URL Rewriting

M66 2025-06-18

Introduction to SEO and URL Rewriting in Yii Framework

In today's digital age, Search Engine Optimization (SEO) is an essential task for any website development. The goal of SEO is to improve a website’s ranking in search engine result pages (SERPs) and attract more user traffic. URL rewriting plays a crucial role in SEO, as it allows you to transform dynamic URLs into clean, meaningful, and static URLs. This makes the website more readable and search engine-friendly. In Yii Framework, we can achieve SEO and URL rewriting functionalities through middleware.

What is Middleware in Yii Framework?

Middleware is a module that operates independently of the controller, and it can process requests before or after they reach the controller. In Yii, we can create custom middleware using the `yii\web\Middleware`.

Creating a Middleware for SEO and URL Rewriting

The first step is to create a class that implements the `Middleware` interface and define the logic for the middleware. Below is an example of middleware that implements SEO optimization and URL rewriting:
<?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);
    }
}

Registering the Middleware in Yii Configuration

After creating the middleware, we need to register it in the application configuration. Open the configuration file `config/web.php` and add the following code:
'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.

Conclusion

With the steps above, we have successfully implemented SEO and URL rewriting middleware in Yii. Now, when users access static pages, the middleware rewrites the URL to the corresponding controller and action, optimizing the website for search engines and making the URLs more user-friendly.

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.