Hello Developers,
This tutorial will show you how to remove the public path from the URL. This will be very helpful in the field of removing duplicate URL creation.
First, we have created a custom function that will remove the public path from the URL. By using the method, you don't need to use .htaccess file. Follow the following code to implement the function.
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->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'));
});
}
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
}
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;
}
}
}
}
I hope this might help you in the journey of development.
Read More : Laravel 8 Remove index php From URL Example