support@codebucket.net

Laravel 8 Remove index php From URL Example

Laravel 8 Remove index php From URL Example

K. M. Shawkat Zamil | September 21, 2022

Hello Developers,

This tutorial will show you how to remove index.php from the URL. This thing will be helpful in making your website more secure. To do that follow my steps.

You have to add some custom code in the RouteServiceProvider file in Laravel. 

 

app/Providers/RouteServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{

    public const HOME = '/home';


    public function boot()
    {
        $this->configureRateLimiting();
        $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'));
        });
    }


    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });
    }


    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;
            }
        }
    }
}

 

I hope this might help you in the journey of development.

 

Read More: Remove Public Path From URL in Laravel Without htaccess

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.