So, you want to use a CDN to manage your static assets! An excellent idea, as CDNs offer multiple advantages: decreased response time, built-in analytics, and sometimes even DDoS mitigation.
As with all Good Things™ , there are some hidden gotchas you should be aware of when first switching to using a CDN for your static assets.
Stop NGINX from serving static assets
This gotcha applies to Rack/Rails Stacks only!
By default, Cloud 66 will place your static assets in the
$STACK_BASE/shared/assets folder on your server, and have NGINX serve them instead of your app - NGINX is much faster at this than your chosen application server.
However, when you switch to using a CDN, your old static assets will still be on the server, and NGINX will still serve them!
This can lead to a few frustrating issues. As mentioned, if the requested asset is on the server, your CDN will be bypassed, and old static assets may be served. You may also experience that some servers have your requested asset, and some don't - thus you get inconsistent responses and headers. Nobody likes Heisenbugs!
The relevant line of NGINX config is the following:
if (!-f $request_filename)
if statement will check whether the requested file exists in the server's static assets folder, and, if it does not, will pass your request on to your application.
With a CDN, you want all requests to be passed to the application.
Lo and Behold, your new NGINX configuration:
Think of the CORS!
Cloud 66 automatically sets up your NGINX to handle CORS, so that it just works.
However, since the CDN will now be returning the static assets instead of your server, you might have to configure your CDN to forward the CORS headers! For example, here is how to do this on CloudFront.
Time is your frenemy
One of the main benefits of using a CDN is that static asset responses are cached on the CDN cloud.
One of the main disadvantages while debugging is that static asset responses are cached on the CDN cloud!
If you are sure that your settings are correct, but are still experiencing problems, try running
curl -I $ASSET_URL (add
-H "Origin: $ACCEPTABLE_ORIGIN" if debugging CORS) and look for the Age header - you might just be getting an old response.
If this is the case, and the CDN is ignoring your Cache-Control headers to bust the cache, you can either wait it out, or try debugging from a server in a different location.
That's All Folks!
My hope is that armed with this knowledge, your switch to using a CDN for your static assets will go much more smoothly!