Laravel: Remove trailing slash from url via middleware
In Laravel, every existing route URL can be utilized both with and without a trailing slash, and you'll receive a HTTP 200
response in either case. However, for search engine optimization purposes, this is not ideal, as the URLs are considered different and therefore result in duplicated content. To address this, simply create a middleware in Laravel and the issue will be resolved.
Create a middleware
php artisan make:middleware RedirectTrailingSlash
Middleware:
app/Http/Middleware/RedirectTrailingSlash.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class RedirectTrailingSlash
{
public function handle(Request $request, Closure $next)
{
if (preg_match('/.+\/$/', $request->getRequestUri())) {
$url = rtrim($request->getRequestUri(), '/');
return redirect($url, 301);
}
return $next($request);
}
}
To register the middleware update your app\Http\Kernel.php
:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\RedirectTrailingSlash::class,
// ...
],
],
I'm a full-stack web developer working with the TALL stack.