Laravel custom middleware for 301 redirection to non index.php url

Laravel custom middleware for 301 redirection to non index.php url

In this Laravel PHP tutorial, I will let you know how to remove index.php from the URL.

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

You can also use .htaccess file to remove the index.php from the URL with 301 redirection but for this example, I will create a custom middleware.

Configure "RemoveIndexPhp" custom middleware

In this step, I will run PHP artisan command to create middleware :

php artisan make:middleware RemoveIndexPhp

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

Now open "RemoveIndexPhp.php" file and update that with 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.

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 ExpertPHP.in";
    });
});

Phone: (+91) 8800417876
Noida, 201301