Remove Public From URL in Laravel Without htaccess

Hello artisan

In this tutorial i am going to show you the way of how to remove public path from url in laravel. It is must needed thing for good seo to avoid duplicate url. I will do this laravel 8 remove public from url without htaccess file.

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

So let's see the example code of laravel 8 public path remove.

app/Providers/RouteServiceProvider.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->removePublicPHPFromURL();
   
        $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 removePublicPHPFromURL()
    {
        if (Str::contains(request()->getRequestUri(), '/public/')) {
            $url = str_replace('public/', '', request()->getRequestUri());
   
            if (strlen($url) > 0) {
                header("Location: $url", true, 301);
                exit;
            }
        }
    }
   
}

 

now if you visit url like bellow then:

https://example.com/public

 

Then you will be redirected to the following url:

https://example.com

 

Read also: Laravel 8 Remove index php From URL Example

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js