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; Let's see how to remove them.
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:
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.
🔴
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; Let's see how to remove them.