You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6 通配符URL重定向实现求助

Got it, let's figure out why your current code isn't working and fix it up!

First, the issue with your existing code: when you use redirect('/somepart2/*'), the * is just a plain string—Laravel doesn't automatically replace it with the content captured by {any}. That means it's redirecting to the fixed URL /somepart2/* instead of the dynamic path you want.

Here are two straightforward solutions to make this work correctly:

1. Use a Closure to Pass the Captured Path

You need to tell Laravel to capture all content after /somepart/ (including nested slashes) and pass that captured value to your redirect target:

Route::get('/somepart/{any}', function ($any) {
    return redirect("/somepart2/{$any}");
})->where('any', '.*');

The ->where('any', '.*') rule is critical here—it lets the {any} parameter match any character (including slashes), so paths like /somepart/x/y/z will be fully captured and appended to /somepart2/.

2. Use Laravel's Built-in Redirect Route

If you don't need custom logic, Laravel has a cleaner shortcut for simple redirects. Just specify the source and target paths, plus an optional redirect status code:

// Use 301 for permanent redirects (good for SEO), 302 for temporary (default)
Route::redirect('/somepart/{any}', '/somepart2/{any}', 301)->where('any', '.*');

This does the exact same thing as the closure method but with less code.

内容的提问来源于stack exchange,提问作者PHPer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:46:02