Laravel multiple domain origin CORS

Sergey picture Sergey · Aug 28, 2018 · Viewed 10k times · Source

I want to allow two domains for CORS in my laravel to be able work with it locally and on the server, thus I don't wan't to expose my app to any domain. That is shat I have for now

public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', 'http://localhost:4200')
//            ->header('Access-Control-Allow-Origin', 'http://api.example.com')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type');
    }

I'm not able to do it neither as I've commented nor as an array

Answer

thefallen picture thefallen · Aug 28, 2018

You can define an array of origins you want to allow and then check the incoming request if its one of them:

public function handle($request, Closure $next)
{
    $allowedOrigins = ['example.com', 'example1.com', 'example2.com'];
    $origin = $_SERVER['HTTP_ORIGIN'];

    if (in_array($origin, $allowedOrigins)) {
        return $next($request)
            ->header('Access-Control-Allow-Origin', $origin)
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type');
    }

    return $next($request);
}