CloudFront in front of WordPress
Disclaimer: this guide is written in March of 2022 and confirmed to work with WordPress 4.9. WordPress will be either self-hosted on an on-premise (homelab) server behind a pfSense 2.7.0 / 22.01 firewall with HAProxy 2.4.9 or on an EC2 instance. We'll make use of the following AWS services: Certificate Manager, Route53, EC2 and CloudFront.
Introduction
In a previous post CloudFront in front of your application I explained how to use CloudFront to cache and protect (DDOS layers 3 and 4) your Ghost or Wiki.js website. The implementation of WordPress behind CloudFront will not be very different and thus I will not create a full guide again, but will refer back to that article.
I implemented this for a test website on our on-premise server and for production websites on EC2. The setups look like this:
1. Setup CloudFront part 1: Create distribution and cache behavior
Create cache policies
Name | Headers | Cookies | Query strings | Compression |
---|---|---|---|---|
CustomOriginWordPressCaching | Origin CloudFront-Is-Tablet-Viewer CloudFront-Forwarded-Proto Referer CloudFront-Is-Mobile-Viewer Host CloudFront-Is-Desktop-Viewer |
comment_author_* comment_author_email_* wordpress_test_cookie comment_author_url_* wordpress_* wordpress_logged_in_* wordpress_sec_* PHPSESSID wp-settings-* |
All | Both |
CustomOriginWordPressNoCaching | Origin CloudFront-Is-Tablet-Viewer CloudFront-Forwarded-Proto Referer CloudFront-Is-Mobile-Viewer Host CloudFront-Is-Desktop-Viewer |
All | All | Both |
Configure origin
See previous post for on-premise servers. For EC2 use HTTP only
on port 80.
Configure default cache behavior
- Compress objects automatically:
Yes
- Viewer protocol policy:
Redirect HTTP to HTTPS
- Allowed HTTP methods:
GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE
- Cache HTTP methods: select
OPTIONS
- Restrict viewer access:
No
- Cache policy:
CustomOriginWordPressCaching
- Origin request policy:
UmamiCORSRequest
Configure settings
See previous post
Add additional cache behaviors
Go to "Behaviors" tab of the distribution and create additional distributions: /wp-login.php
, /wp-admin/*
, /wp-json/*
, /contact/
, /wp-signup.php
, /wp-trackback.php
, /xmlrpc.php
and /wp-cron.php
.
- Compress objects automatically:
Yes
- Viewer protocol policy:
Redirect HTTP to HTTPS
- Allowed HTTP methods:
GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE
- Cache HTTP methods: select
OPTIONS
- Restrict viewer access:
No
- Cache policy:
CustomOriginWordPressNoCaching
- Origin request policy:
None
2. Security
By selecting port 80 to connect CloudFront to the EC2 origin, all traffic will be unencrypted. As long as this traffic is within AWS, this is not a big deal and it offloads the SSL burden from our EC2 to CloudFront. In the next post I'll explain how to limit access to our WordPress website to our CloudFront distribution.
Sources
To get to this setup I used multiple sources and combined them: