Laravel子域名路由未按预期运行:admin子域名访问仍匹配web路由
问题原因
- Laravel 路由按注册顺序从上到下依次匹配,你定义的
web路由组没有添加域名约束,会适配所有域名的请求。 - 你访问
admin.mywebsite.com/test时,首先校验admin子域名路由组,由于admin.php中没有定义/test路由,匹配失败;接着校验api子域名路由组,同样无对应路由匹配失败;最终命中无域名限制的web路由组中的/test规则,返回对应响应。
修复方法
给web路由组添加根域名绑定,限制它仅响应根域名的请求,修改RouteServiceProvider中web路由的注册代码即可:
public function boot() { $this->configureRateLimiting(); $this->routes(function () { Route::domain("admin." . env("APP_URL")) ->namespace($this->namespace) ->group(base_path("routes/admin.php")); Route::domain("api." . env("APP_URL")) ->middleware("api") ->namespace($this->namespace) ->group(base_path("routes/api.php")); // 新增domain约束,仅匹配根域名 Route::domain(env("APP_URL")) ->middleware("web") ->namespace($this->namespace) ->group(base_path("routes/web.php")); }); }
内容的提问来源于stack exchange,提问作者Eyad Bereh
相关产品推荐
相关产品推荐

