There are roughly a GAJILLION articles, blogs, and documents out there that explain how to setup Amazon CloudFront to work with WordPress.
Most of them are wrong in one or more ways.
- They advise a type of cache behavior that is incorrect for one or more WordPress assets.
- They fail to provide any advice for WordPress assets that need specific cache behavior.
- The article/blog/document is stale and hasn't been updated to reflect changes in newer versions of WordPress.
Rather than fall into the trap of writing yet another article for whatever the "now current" version of WordPress is that will likely fall victim to one or more of the conditions listed above, I'm going to take a different approach.
I'm going to codify the CloudFront configuration, version it on GitHub, and adopt an "infrastructure-as-code" (IaC) mentality. This blog post will describe the overall architecture and provide some context, but the actual mechanics of setting up CloudFront to work with WordPress will live (and evolve!) in the IaC files themselves which will be under version control.
Let's do it!
I'll say this up front: this architecture may not be for everyone (but I have a sneaky suspicion it might be for the majority of folk). My intention is really simple:
- Have functioning WordPress site
- Put CloudFront in front of said site
- Blog the experience
Notice what's not in that list:
- Storing static assets like images, CSS, etc, on S3
- Running a fancy dancy caching plugin that talks to CloudFront for things like invalidation
- Moving the WordPress site to an auto-scaling EC2 farm with a loadbalancer
- And literally everything else one can think of that isn't #1, #2, or #3
Here's what the architecture looks like:
When users browse to the blog site
www.example.ca, DNS sends them to CloudFront. CloudFront answers for that name and will promptly check the user's request, look at the list of cache behaviors, apply the right behavior, and then either fetch content from cache or request content from the origin (which is called
origin.example.ca) and return that content to the user. That's it, that's all. Simple.
I've used Terraform to manage the infrastructure in this case and am versioning the Terraform manifest files on GitHub. And in the spirit of IaC, I've also documented how to use the manifest files in the same repo (keeping the docs and code together, you see).
Head on over to the GitHub repo to grab the code and get going. If you see something lacking, please submit a pull request!
- What is Amazon CloudFront?
- Amazon CloudFront Request and Response Behavior for Custom Origins
- Values That You Specify When You Create or Update a CloudFront Distribution
- Getting Started with Terraform
- The Terraform AWS provider
Disclaimer: The opinions and information expressed in this blog article are my own and not necessarily those of Amazon Web Services or Amazon, Inc.