Remove index.php from Laravel Urls
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.
Copied!
1/blog/some-article2/index.php/blog/some-article
To remove this behavior create a new middleware:
Copied!
1php artisan make:middleware RemoveIndexMiddleware
add the following contents
Copied!
1<?php 2 3namespace App\Http\Middleware; 4 5use Closure; 6use Illuminate\Http\Request; 7use Illuminate\Support\Str; 8 9class RemoveIndexMiddleware10{11 /**12 * Handle an incoming request.13 *14 * @param \Illuminate\Http\Request $request15 * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next16 * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse17 */18 public function handle(Request $request, Closure $next)19 {20 $request_uri = Str::start($request->getRequestUri(), '/');21 if (Str::startsWith($request_uri, '/index.php')) {2223 $clean_url = $request->getSchemeAndHttpHost();24 $clean_url .= Str::start(Str::replaceFirst('/index.php', '', $request_uri), '/');2526 return redirect($clean_url, 301);27 }2829 return $next($request);30 }31}
Update app/Http/Kernel.php
and in the application's global HTTP middleware stack, add your new middleware:
Copied!
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.