NGINX – Fixing CORS Policy Issues with Font Files

cdncorsnginx

I have added the following headers to all the locations where my static content is mentioned in the Nginx conf file and it removes the CORS issue for all files except for font files such as woff2 or ttf.

location /static/ {
# Uncomment the following line in production mode
# expires max;
add_header 'Access-Control-Allow-Origin' '*' 'always';

if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*' 'always';
    add_header 'Access-Control-Allow-Headers' 'x-requested-with' 'always';
    add_header 'Access-Control-Max-Age' 86400 'always';
    add_header 'Content-Length' 0 'always';
    return 204;
}

# Remove signature of the static files that are used to overcome the browser cache
location ~ ^/static/version {
    rewrite ^/static/(version\d*/)?(.*)$ /static/$2 last;
}

location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2|json)$ {
    add_header 'Access-Control-Allow-Origin' '*' 'always';

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*' 'always';
        add_header 'Access-Control-Allow-Headers' 'x-requested-with' 'always';
        add_header 'Access-Control-Max-Age' 86400 'always';
        add_header 'Content-Length' 0 'always';
        return 204;
    }
    add_header Cache-Control "public";
    #add_header X-Frame-Options "SAMEORIGIN";
    expires +1y;

    if (!-f $request_filename) {
        rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
    }
}
location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
    add_header Cache-Control "no-store";
    #add_header X-Frame-Options "SAMEORIGIN";
    expires    off;

    if (!-f $request_filename) {
       rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
    }
}
if (!-f $request_filename) {
    rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
}
#add_header X-Frame-Options "SAMEORIGIN";
}

Here is the error msg:

Access to the font at
'https://static.magento-test.mysite.com/adminhtml/Magento/backend/en_US/fonts/opensans/bold/opensans-700.woff2'
from origin 'https://magento-test.mysite.com' has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource. (index):762 GET
https://static.magento-test.summerraingroup.com/adminhtml/Magento/backend/en_US/fonts/opensans/bold/opensans-700.woff2
net::ERR_FAILED

I don't get why I still get the CORS issue. Any idea?

Best Answer

In order to allow the header to be updated after changing the nginx configuration file, you need to flush your CDN. Once flushed, the correct header is applied to the files and the CORS disappears as expected.

Related Topic