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
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
sakarya escort | sakarya escort | adapazarı escort | sakarya escort | sakarya escort | sapanca escort | sakarya escort | sakarya escort | serdivan escort | sakarya escort | karasu escort | sakarya escort | sakarya escort | sapanca escort | sakarya escort | sakarya escort | sakarya escort | sapanca escort | sakarya escort | hendek escort bayan sakarya escort adresleri.