Laravel子域名API路由优先匹配web路由,如何修复?
Laravel子域名API路由优先级问题修复方案
调整路由注册顺序
Laravel的路由匹配遵循先注册先匹配的规则,打开app/Providers/RouteServiceProvider.php,在map方法里把API路由的注册放在Web路由前面:public function map() { $this->mapApiRoutes(); // 先注册API路由 $this->mapWebRoutes(); // 再注册Web路由 }精准设置API路由的域名约束
在mapApiRoutes方法中,明确指定api子域名,避免模糊匹配导致的优先级混乱:protected function mapApiRoutes() { Route::domain('api.example.test') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); }修正Web路由的域名范围
如果Web路由配置了泛域名(比如*.example.test),会把api子域名的请求也纳入匹配范围。将Web路由的域名改为精准的主域名:protected function mapWebRoutes() { Route::domain('example.test') ->middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); }清除路由缓存
执行命令清除本地路由缓存,避免旧规则干扰新配置:php artisan route:clear
内容的提问来源于stack exchange,提问作者Shiref
相关产品推荐
相关产品推荐

