How to Redirect Uppercase URLs to Lowercase with Laravel Middleware

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.


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RedirectUppercase
     * Handle an incoming request.
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $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.


return Application::configure(basePath: dirname(__DIR__))
        // ...
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->appendToGroup('web', \App\Http\Middleware\RedirectUppercase::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.

Read more

© 2024 Extly, CB - All rights reserved.