Faster websites are better. Better experience, better sales, you name it. Unfortunately, making a website faster can be tough. Thankfully a content distribution network, or CDN, can give you great performance bang for your buck. A CDN helps speed things up by putting copies of your files closer to your users. It's like the difference between pizza delivery from across the street and pizza delivery from the next town over.
The ease and deliciousness are the good news, but until recently CDN's were only available in the big leagues via 'my business guys will talk to your business guys' deals. Fortunately for us, Amazon recently updated CloudFront, their CDN service, to allow us to get these benefits with just a credit card and an API call. So now we'll see how you can spend a few minutes to save your users countless hours of load time.
First, make sure you have fog installed:
gem install fog
Now you'll need to sign up for Cloudfront. Gather up the credentials your new credentials to initialize a connection to the service:
Setting Up Your CDN
Now you'll need to create a 'distribution' which represents a mapping from the CDN to your domain. For the examples we'll pretend we are working on 'http://www.example.com', but you can just switch it to your actual domain. Some other options are available, but the only other one we need to fill in is OriginProtocolPolicy. This sets what to do about http vs https. We will use 'match-viewer' which returns the same protocol as the request, but you can also choose 'http-only' which always returns http responses.
With the domain name from the distribution in hand you should now be ready to serve content from the edge. All you need to do is start replacing urls like
Congrats, your site is faster! By default the urls aren't very pretty, something like
http://d1xdx2sah5udd0.cloudfront.net/stylesheets/foo.css. Thankfully you can use CNAME config options to utilize something like
http://assets.example.com/stylesheets/foo.css, if you are interested in learning more about this let me know in the comments.
But, just in case you need to update things I'll run through how you can make changes. In my case I just want to clean up after myself, so I'll use the distribution_id and ETag from before to disable the distribution. We need to use the ETag as well because it provides a way to refer to different versions of the same distribution and ensures we are updating the version that we think we are.
Now you just need to wait for the update to happen like before and once its disabled we can delete it:
Thats it, now go forth and speed up some load times!