Laravel 8 Remove Index Php From URL Example

Hello artisan

In this tutorial i am going to show you the way of remove public/index.php from laravel url. It is must needed task for good seo to avoid duplicate url in a website. I will do this laravel 8 remove index php from url without htaccess file.

I will simply create our own custom code to remove laravel remove index in laravel application. So from this example you will learn laravel 8 remove index php from url without htaccess.

So let's see the example code of remove index.php file from url in Laravel.

app/Providers/AppServiceProvider.php

namespace App\Providers;
   
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
   
class RouteServiceProvider extends ServiceProvider
{
    public const HOME = '/home';

    public function boot()
    {
        $this->removeIndexFromUrl();
   
        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
  
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }
   
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected function removeIndexFromUrl()
    {
        if (Str::contains(request()->getRequestUri(), '/index.php/')) {
            $url = str_replace('index.php/', '', request()->getRequestUri());
   
            if (strlen($url) > 0) {
                header("Location: $url", true, 301);
                exit;
            }
        }
    }
   
}

 

now if you visit url like bellow then:

https://example.com/index.php

 

Then you will be redirected to the following url:

https://example.com

 

Read also: Remove Public From URL in Laravel Without htaccess

 

Hope it can help you.

 

#laravel #laravel-8x