Remove index.php from the URL in Laravel

Published 23 November 2019 14:59 (2-minute read)

I've discovered an unwanted behaviour in one of my projects. This was not used to be so, Google indexed a url with index.php in it and gave a duplicate canonical notification.

It happend on a URL like this:

After I noticed it, I want to other known Laravel projects and discovered the same.

And also on the Laravel website self.

I contacted Mattias Geniar (from OhDear!) and he was really quick with a solution. The solution can be found on his personal blog,

Personally I like this approach, because it's a known issue so it should be fixed in the framework itself and not on the server, like in nginx.


use Illuminate\Support\Str;

class RouteServiceProvider extends ServiceProvider
    public function map(Router $router)

     * This will remove the index.php from the URL and prevent canonical conflicts.
     * @return void	
    protected function removeIndexPhpFromUrl()
        if (Str::contains(request()->getRequestUri(), '/index.php/')) {
            $url = str_replace('index.php/', '', request()->getRequestUri());

            if (strlen($url) > 0) {
                header("Location: $url", true, 301);

Robin Dirksen
Robin Dirksen

Follow me on Twitter, there I post web-related content, tips/tricks, and other interesting things.

On my blog, you can find articles that I've found useful or wanted to share with anyone else.

If you want to know more about this article or just want to talk to me, don't hesitate to reach out.