Laravel subdomain route matching issue

Viewed 344

I need to implement subdomain for api routes, but I'm getting 404 error

I have APP_URL set to http://example.com

I've configured subdomain in RouteServiceProvider

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

I see that problem is in Illuminate\Routing\Matching\HostValidator when it calls $request->getHost() it returns 'example.com', not 'api.example.com'. If i change APP_URL to http://api.example.com it works well.

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());
    }
}

Looks like i missed some configuration, but I haven't found any additional configuration requirements in laravel docs.

"laravel/framework": "^7.12"

ADDITIONAL: so currently i can see that laravel redirects api.example.com to example.com, so that's why I'm getting host validation error.

The next question is - Why it does redirect? =)

1 Answers

I don't think it will help somebody, but the answer was in one middleware which I've found in project. It was redirecting all invalid hosts (non APP_URL) to 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);
Related