编程

通过 Laravel 中间件将大写字母的网址重定向到小写 URL

247 2024-08-12 05:23:00

有时为了 SEO 优化,我们会将包含大写字母的请求重定向到小写字母 URL 中。

比如:

FromTo
/location/Atlanta/location/atlanta
/docs/Laravel-Middleware/docs/laravel-middleware

同时,解决方案不能修改查询参数:

FromTo
/locations/United-States?search=Georgia/location/united-states?search=Georgia

事实证明,在 Laravel 中间件中,我们只需几行代码就可以做到这一点!首先,我们从请求中获取路径,并检查其是否为小写。如果不是,我们可以使用 url()->query() 方法将查询字符串附加回路径的小写版本,并永久重定向到小写路径。

<?php
 
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);
    }
}

要在 Laravel 11 中注册中间件,我在 bootstrap/app.php 文件中将其附加到 web 中间件分组。

<?php
 
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        // ...
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->appendToGroup('web', \App\Http\Middleware\RedirectUppercase::class);
    });

注意:你可能需要将此中间件从使用签名 URL 或其他区分大小写的用例的路由中排除。

我确定 Nginx 或 Apache 也有可能提供解决方案,但这对我来说是迄今为止最简单的解决方案,它适用于应用的所有环境。我不必记得在新服务器上做任何更改。