Remove the public or index.php folder from the URL in Laravel

Many times when we are developing a project in Laravel and move it to production, we see errors that appear in the URL, the public folder or the index.php file:

// Valid URL
https://example.com/blog
// Invalid URL
https://example.com/index.php/blog

https://example.com/public/blog

Which, if we have a blog, this can bring us penalties with SEO; In this entry we are going to see how to repair this problem, not from htaccess, which many times does not work and there are many examples of how to do it on the Internet, but rather, using PHP code, therefore, if you are desperate, this is the last one. measure you can implement.

To remove the public folder and/or index.php from the URL, what we must do is go to the provider of our application:

app/Providers/AppServiceProvider.php

Which is a kind of middleware, and we create a function like the following:

app/Providers/AppServiceProvider.php

<?php
namespace App\Providers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
class AppServiceProvider extends ServiceProvider
{
   public function boot(): void
   {
       $this->removePublicPHPFromURL();
   }
   protected function removePublicPHPFromURL()
   {
       if (Str::contains(request()->getRequestUri(), '/public/')) {
           $url = str_replace('public/', '', request()->getRequestUri());
 
           if (strlen($url) > 0) {
               header("Location: $url", true, 301);
               exit;
           }
       }
   }
}

Or if you want to remove the index.php, it looks like this:

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

In both cases, as you can see, we simply verify through the request, if the index.php folder or the public folder exists and we remove it, then, we do a 301 redirect which means that it indicates that it is a permanent redirect to it URL by removing the public and index.php folder.

- Andrés Cruz

En español

This material is part of my complete course and book; You can purchase them from the books and/or courses section, Curso y libro Laravel 11 con Tailwind Vue 3, introducción a Jetstream Livewire e Inerta desde cero - 2024.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.