Laravel multiple domain origin CORS
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);
}
@thefallen 's answer works for me, also I had the @sergey 's same problem, I solved like this.
public function handle($request, Closure $next)
{
$allowedOrigins = [env('FRONTEND_ENDPOINT', 'http://localhost:8080'), env('WORDPRESS_ENDPOINT', 'http://localhost'), env('EXTRA_ENDPOINT', 'http://127.0.0.1')];
if($request->server('HTTP_ORIGIN')){
if (in_array($request->server('HTTP_ORIGIN'), $allowedOrigins)) {
return $next($request)
->header('Access-Control-Allow-Origin', $request->server('HTTP_ORIGIN'))
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
->header('Access-Control-Allow-Headers', '*');
}
}
return $next($request);
}
this way you can also just set the variables in .env file like this.
FRONTEND_ENDPOINT=http://localhost:8080
WORDPRESS_ENDPOINT=http://localhost
EXTRA_ENDPOINT=http://127.0.0.1:8080