Jose Jimenez
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.

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

To remove this behavior create a new middleware:

1php artisan make:middleware RemoveIndexMiddleware

add the following contents

 1<?php
 2
3namespace App\Http\Middleware;
 4
5use Closure;
6use Illuminate\Http\Request;
7use Illuminate\Support\Str;
 8
9class RemoveIndexMiddleware
10{
11 /**
12 * Handle an incoming request.
13 *
14 * @param \Illuminate\Http\Request $request
15 * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
16 * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
17 */
18 public function handle(Request $request, Closure $next)
19 {
20 $request_uri = Str::start($request->getRequestUri(), '/');
21 if (Str::startsWith($request_uri, '/index.php')) {
22
23 $clean_url = $request->getSchemeAndHttpHost();
24 $clean_url .= Str::start(Str::replaceFirst('/index.php', '', $request_uri), '/');
25
26 return redirect($clean_url, 301);
27 }
28
29 return $next($request);
30 }
31}

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

1protected $middleware = [
2 // .
3 // ..
4 // ...
5 \App\Http\Middleware\RemoveIndexMiddleware::class,
6]

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