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
Attention Required! | Cloudflare

Sorry, you have been blocked

You are unable to access ressim.net

Why have I been blocked?

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.