Last week, I needed to redirect all requests that contained uppercase letters to their lowercase equivalents for SEO optimization.
For example:
From
To
/location/Atlanta
/location/atlanta
/docs/Laravel-Middleware
/docs/laravel-middleware
At the same time, the solution shouldn’t change any query parameters:
From
To
/locations/United-States?search=Georgia
/location/united-states?search=Georgia
It turns out we can do this with just a few lines of code in a Laravel middleware! First, we grab the path from the request and check if the it is the same lowercased. If not, we can use the url()->query() method to append the query string back onto the lowercase version of the path and permanently redirect to the lowercased path.
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
use SymfonyComponentHttpFoundationResponse;
class RedirectUppercase
{
/**
* Handle an incoming request.
*
* @param Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse) $next
*/
public function handle(Request $request, Closure $next): Response
{
$path = $request->path();
if (($lower = strtolower($path)) !== $path) {
$url = url()->query($lower, $request->query());
return redirect($url, 301);
}
return $next($request);
}
}
To register the middleware in a Laravel 11 app, I appended it to the web middleware group in the bootstrap/app.php file.
<?php
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
// …
)
->withMiddleware(function (Middleware $middleware) {
$middleware->appendToGroup(‘web’, AppHttpMiddlewareRedirectUppercase::class);
});
Note: you may want to exclude this middleware from routes that use signed URLs or other case sensitive use-cases.
I’m sure there are possible solutions with Nginx or Apache, but this was by far the simplest solution for me and it works across all environments of the app. I don’t have to remember to make any changes on new servers.
The post How to Redirect Uppercase URLs to Lowercase with Laravel Middleware appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.
Source: Read MoreÂ