Laravel链接URL路径正确却始终跳转至首页问题求助
问题根源
路由匹配顺序错误导致的。你把带动态参数{locale}的路由分组放在了/about、/contact这类静态路由前面,Laravel会按路由定义的顺序匹配请求:当访问/about时,框架会把about当成locale参数,直接匹配分组里的根路由(/{locale}/),所以返回的是首页内容,根本没走到/about对应的路由逻辑。
解决方案
调整路由定义顺序,把静态路由放在动态前缀的路由分组之前,让框架优先匹配静态路径:
Route::get('/',function(){ return redirect(app()->getLocale()); })->name('root'); // 先定义静态路由 Route::get('/about',function(){ return view('about'); })->name('about'); Route::get('/contact',function(){ return view('contact'); })->name('contact'); // 再定义带动态locale前缀的路由分组 Route::group(['prefix'=>'{locale}','middleware'=>'setLocale'],function(){ Route::get('/',[FrontEndController::class, 'index'])->name('index'); });
额外建议:给{locale}参数添加匹配约束,避免任意字符串被误判为语言标识,比如只允许指定的语言代码:
Route::group(['prefix'=>'{locale}','middleware'=>'setLocale','where'=>['locale'=>'en|zh']],function(){ Route::get('/',[FrontEndController::class, 'index'])->name('index'); });
内容的提问来源于stack exchange,提问作者Maher Fakhour
相关产品推荐
相关产品推荐

