Laravel : add Cors header for static files

2019-06-14 08:34发布

问题:

I have a Laravel app, which was hosted on Apache, but now has been migrated on nginx. I'm a totally newbie with nginx.
On Apache I had this in my htaccess :

<IfModule mod_headers.c> <FilesMatch "\.(svg|ttf|otf|eot|woff|woff2)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch> </IfModule>

The new hosting provider does not allow custom nginx configuration.

Is it possible to add a Cors header (Access-Control-Allow-Origin: *) for static font files (extensions : svg|ttf|otf|eot|woff|woff2) in the Laravel app PHP code ? I tried (Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport) without success, my guess is that static files are not targeted by that piece of code. Do you confirm ?

Is there a way to achieve this within my app's PHP code ?

thanks

回答1:

Use this in you server block or nginx.conf to apply globally.

location ~* \.(svg|ttf|otf|eot|woff|woff2)$ {
    add_header Access-Control-Allow-Origin *;
}

Make sure to restart nginx server for changes to take effect.