Adding CORS header to static assets in Laravel App

Image from Stencil

Sometimes we need to fetch static resources (PDF files, images, videos etc)from a server via a HTTP client in the browser, eg. AJAX, Fetch or Axios. So we try this in JavaScript:

But we see our good old friend CORS error :)

But you’ve already added Laravel CORS config? All the other API routes work perfectly fine except for static resources?

Why??

Well it turns out when we request static resources, the web server will serve them directly without passing the HTTP request through Laravel.

Since the PHP code in Laravel doesn’t run, the CORS middleware will not run, and therefore the CORS headers are not added to the HTTP response.

Solution

Before you slam your head against the wall, try to add the following to your server config.

For NGINX users

In the server block

For Apache users

For Apache servers, add the following to your .htaccess .

That’s it!

Web Development. https://acadea.io/learn . Follow me on Youtube: https://www.youtube.com/c/acadeaio

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store