【问题标题】:Laravel subdomain route matching issueLaravel 子域路由匹配问题
【发布时间】:2020-06-26 09:39:02
【问题描述】:

我需要为 api 路由实现子域,但出现 404 错误

我将 APP_URL 设置为 http://example.com

我已经在 RouteServiceProvider 中配置了子域

protected function mapApiRoutes()
    {
    
        Route::domain('api.example.com')
            ->prefix('/api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));
    }

我看到问题出在 Illuminate\Routing\Matching\HostValidator 中,当它调用 $request->getHost() 时它返回“example.com”,而不是“api.example.com”。如果我将 APP_URL 更改为 http://api.example.com 效果很好。

class HostValidator implements ValidatorInterface
{
    /**
     * Validate a given rule against a route and request.
     *
     * @param  \Illuminate\Routing\Route  $route
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    public function matches(Route $route, Request $request)
    {
        $hostRegex = $route->getCompiled()->getHostRegex();

        $host = $request->getHost();
        
        if (is_null($hostRegex)) {
            return true;
        }

        return preg_match($hostRegex, $request->getHost());
    }
}

看起来我错过了一些配置,但我在laravel docs 中没有找到任何额外的配置要求。

“laravel/框架”:“^7.12”

附加:所以目前我可以看到 laravel 将 api.example.com 重定向到 example.com,这就是我收到主机验证错误的原因。

下一个问题是 - 为什么它会重定向? =)

【问题讨论】:

    标签: laravel


    【解决方案1】:

    我认为它不会对某人有所帮助,但答案是在我在 project.xml 中找到的一个中间件中。它将所有无效主机(非 APP_URL)重定向到 APP_URL:

    if (auth()->user() == null && $request->getSchemeAndHttpHost() != $this->config->get('app.url')) {
                $additional = '';
    
                if ($request->input()) {
                    $additional .= '?' . http_build_query($request->input());
                }
    
                return redirect()->secure($this->config->get('app.url') . $request->getPathInfo() . $additional);
            }
    
            return $next($request);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-03
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 2018-03-01
      • 2020-01-04
      相关资源
      最近更新 更多