為優化搜索引擎優化 (SEO),我上週需要將所有包含大寫字母的請求重定向到其小寫等效項。
例如:
源 URL | 目标 URL |
---|---|
/location/Atlanta | /location/atlanta |
/docs/Laravel-Middleware | /docs/laravel-middleware |
同時,此解決方案不應更改任何查詢參數:
源 URL | 目标 URL |
---|---|
/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 { /** * 处理传入请求。 * * @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()->to($lower)->appendQuery($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 來實現,但這對我來說是迄今為止最簡單的解決方案,並且它適用於應用程序的所有環境。我不必記住在新服務器上進行任何更改。
以上是如何將大寫URL重新定向使用Laravel中間件的詳細內容。更多資訊請關注PHP中文網其他相關文章!