Laravel create custom middleware for 301 redirections to non index.php url

In today’s tutorial, we will learn how to create custom middleware for 301 redirections to non index.php URL.

Having index.php in the URL is not good for the SEO practice.

We can use .htaccess file to remove the index.php from the URL, which is also a very easy integration. But today we will only explain this via Laravel and creating middleware and defining login in it.

Configure “RemoveIndexPhp” custom middleware

In this step, let’s run the PHP artisan command to create middleware in which we will define the logic to remove the index.php.

php artisan make:middleware RemoveIndexPhp

After running the above command, you will have a middleware file in the following directory app/Http/Middleware/.

Now open the “RemoveIndexPhp.php” file and update that with the below code :

<?php

namespace App\Http\Middleware;

use Closure;

class RemoveIndexPhp
{

    public function handle($request, Closure $next)
    {
        $searchFor = "index.php";
        $strPosition = strpos($request->fullUrl(), $searchFor);
        if ($strPosition !== false) {
            $url = substr($request->fullUrl(), $strPosition + strlen($searchFor));
            return redirect(config('app.url') . $url, 301);
        }
        return $next($request);
    }
}

Now register this middleware as routeMiddleware in the Kernel.php file. It’s mandatory when we create a middleware then we need to get it registered in the Kernel file.

app/Http/Kernel.php :

protected $routeMiddleware = [
        ....
        'RemoveIndexPhp' => \App\Http\Middleware\RemoveIndexPhp::class,
    ];

Add route

To test this example, I need to add a single route inside the group middleware :

Route::group(array('middleware' => ['RemoveIndexPhp']), function ()
{
    Route::get('/',function(){
        return "Welcome to www.atcodex.com";
    });
});

Recommended Posts For You