Solving "No 'Access-Control-Allow-Origin' header is present on the requested resource" issues

We all know this annoying error when requesting resources over the network from a domain that different than the one that serves our web app. For content that is served by an API, this is quite straight-forward to solve: just modify your apps to accept and respond to these cross-domain requests. However, for static files this might be a bit tricky as there is no app that serves the file, but it's served directly from the server, 100% static. This situation most likely appears when you have a CDN that serves assets from an origin that is also managed by you.

Let's consider this case for NakedSSL: we have the app living on app.nakedssl.com and the CDN living on cdn.nakedssl.com. The CDN is configured in a way that, when requesting cdn.nakedssl.com/assets/*, it will fetch assets from app.nakedssl.com/assets/* and serve them under cdn.nakedssl.com/assets/*. What may happen when our app tries to load assets from cdn.nakedssl.com? Yep, exactly: I'll most likely get the damn "No 'Access-Control-Allow-Origin' header is present on the requested resource" error in the browser.

While the issue might a bit hard to explain and even harder to notice it before you experience it, it is super easy to solve: it is as simple as allowing cross-domain requests on your origin. You can do that by just adding this piece of code to the VirtualHost file that controls the origin from where the CDN requests the assets:

If you use Nginx:

location ~* .
(json|gif|jpg|jpeg|png|ico|wmv|3gp|avi|mpg|mpeg|mp4|flv|mp3|mid|js|css|wml|swf|ttf|ttc|otf|eot|woff|woff2)$ {

add_header Access-Control-Allow-Origin "*";
expires max;

}

If you use Apache:

# Allow access from all domains for webfonts.
# Alternatively you could only whitelist your
# subdomains like "subdomain.example.com".

<IfModule mod_headers.c>
<FilesMatch "\.
(json|gif|jpg|jpeg|png|ico|wmv|3gp|avi|mpg|mpeg|mp4|flv|mp3|mid|js|css|wml|swf|ttf|ttc|otf|eot|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>

And voila! Error most likely solved. If this still does not solve the error, there might be one more thing left to do: ensure that your CDN is configured to forward headers from/to your client and origin.