Should i add my CORS Header in nginx.conf or with Laravel config/cors.php?

I'm currently configuring my nginx server for a laravel application and added the Access-Control-Allow-Origin header. Suddenly my browser threw an error saying that there are multiple header values present for this key. Turns out there's a cors.php configuration available in Laravel. Now i'm a bit confused whether it's a good idea to let this header be handled by the php application itself or whether my nginx server should be responsible for this.

Is there a best practice on how to deal with this?

Answer

Solution:

Using laravels cors feature, you can attach the cors headers to specific routes. But you can only attach it on laravel routes, your static assets such as css files, js, images, fonts, etc will not be covered by the cors since they are accessed directly from filesystem without entering the laravel application.

On the other hand, if you set cors in nginx, it will affect all requests ( or based on how you configure )

So based on your requirement, you can choose which you need. If you need the cors headers for everything, you'll need to set the header through nginx. If you instead need cors only for some specific routes ( such as all routes starting with /api ) then you can use laravels cors

Source