1

I have Magento 2.3.2 with nginx backend, SSL only, and proxypass to Varnish.

I have configured 2 distributions in my cloudfront CDN to serve media and static files.

To handle the CORS issues I have modified my nginx configuration file the following way:

location /static/ {
    # Uncomment the following line in production mode
    # expires max;

    # Remove signature of the static files that is 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 Cache-Control "public";
        add_header X-Frame-Options "SAMEORIGIN";
        include /etc/nginx/magento2-cors.conf;
        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";
        include /etc/nginx/magento2-cors.conf;
        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";
    include /etc/nginx/magento2-cors.conf;
}

The magento2-cors.conf snippet contains the following:

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;
}

With this configuration I still have issues with html files being blocked by CORS. Because I am not sure if it is a good idea to whitelist CORS for all HTML files in my static folder, I have created a behavior in my Cloudfront config to not cache any html file and get it directly from origin (ie my static folder on the server). However, if I do not warm Varnish, then somehow I still get a CORS error. The funny part is that the CORS mention the origin as being my server.... which is not supposed to return CORS issue. I noticed that if I refresh the page, ie Varnish will hit, then the CORS error disappears. Any idea how to handle this issue ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.