Jose Jimenez
Software Architect & Developer
> >

Remove index.php from Laravel Urls

Published in PHP, Laravel, SEO on Sep 8, 2022

It is currently possible to access your application from both two different URLS which could affect your SEO.

The benefit of doing it as a middleware in the application is that it will work regardless of the server environment, i.e. you run running Apache, NGINX, or something else.

/blog/some-article
/index.php/blog/some-article

To remove this behavior create a new middleware:

php artisan make:middleware RemoveIndexMiddleware

add the following contents

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class RemoveIndexMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $request_uri = Str::start($request->getRequestUri(), '/');
        if (Str::startsWith($request_uri, '/index.php')) {

            $clean_url = $request->getSchemeAndHttpHost();
            $clean_url .= Str::start(Str::replaceFirst('/index.php', '', $request_uri), '/');

            return redirect($clean_url,  301);
        }

        return $next($request);
    }
}

Update app/Http/Kernel.php and in the application's global HTTP middleware stack, add your new middleware:

protected $middleware = [
	// .
	// ..
	// ...
	\App\Http\Middleware\RemoveIndexMiddleware::class,
]

Now urls with /index.php will have a permanent redirect not affecting your SEO.