Get started with CloudFront - Part 2: Distribution Invalidations
Tags: aws, cloudskills, network, community
Published: 2023-03-01 19:49:08

#### Table of Content

1. [Test Distribution Invalidations]()
2. [Custom Error Page]()
3. [Create Origin Group]()

#### 1. Test Distribution Invalidations
When using **Amazon CloudFront** to distribute resources to the website, some resources will be stored in CloudFront's cache to speed up access for users. However, when you make changes to a cached resource but cannot change the URL to point to the new version, you need to perform Invalidations to discard the old version and reload the session. new version from the original server.

Access the **Invalidations tab** on the **CloudFront** Console interface.

- Create an **Invalidation** for the **index.html** resource.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8k1kwzxew1mqnxh3et34.png)

You can specify / in Object paths because we have set index.html as default root object.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qrhzqhdhkvumajt7sa23.png)

Invalidations in progress


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/baq7nidize5p0cur38mj.png)

Create successful Invalidations


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rcs48wjadhsprcmxy3aw.png)

After a few seconds, retry the site using the browser developer tool, you will see that it is no longer cached by CloudFront and reload a new version from the origin server.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j1yrjrcvz2ljo40ooc85.png)

Note: Invalidations may take a few minutes to complete, and during that time, users may be able to access an older version of the resource. Therefore, you need to consider and perform Invalidations at the right time to ensure the latest resources are delivered to users.

The data shows that when you perform Invalidations, if a resource is already cached in CloudFront, it will be removed from the cache and a new version will be downloaded from the origin server when the user requests access. access that resource. This helps ensure that users receive the latest version of the resource without having to clear the browser cache or wait for the CloudFront cache to expire.

Using Invalidations in Amazon CloudFront also saves costs and increases the performance of your website. When a resource is stored in CloudFront's cache, downloading it from the origin server consumes a lot of your time and system resources. When you use Invalidations to remove old versions, CloudFront will no longer have to reload these old versions, saving resources and reducing your website's operating costs.

In short, Invalidations is an important tool that helps ensure that users receive the latest version of the resource and helps speed up the website. It also saves resources and lowers your website's operating costs.


#### 2. Custom Error Page

When testing a random URL with your CloudFront domain, you will get a 403 Forbidden response from S3 behind CloudFront because the file doesn't exist. By default, CloudFront temporarily stores this response for 10 seconds.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/os9cztdtf54gce71yaqb.png)

Create the error.html file on your computer using a text editor with the HTML content below and upload it to your S3 bucket as you did before for the index.html file.

- Open a text editor on your computer
- If you use Windows, you can use Notepad or Notepad++ to edit text
- If you use MacOS, you can use TextEdit or other text editors to edit text
- Create error.html file with HTML content below:

```
<html lang="en">
  <body>
    <h1>CloudFront Lab</h1>
    <strong>Ops, this is a nice error page!</strong>
  </body>
</html>
```

- Save the error.html file with UTF-8 format and give the file an arbitrary name (eg error.html)

- Log in to AWS Console and select the S3 . service

- Select the S3 bucket where you want to upload the error.html . file




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oo5wr29cwd3kbhvoks6u.png)

Select "Upload" to upload the error.html file from your computer to the S3 bucket




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtvzpigsyyc1kvj1kmty.png)

Wait for the upload to complete


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4b5kk7u9wso74a4v63xk.png)

To check if the error.html file has been uploaded successfully, select it on the S3 bucket and preview its contents.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/znp7ufsqrh3vrdq2r43a.png)

#### Instructions for configuring a custom error page in CloudFront

To configure a custom error page in CloudFront, you can do the following:

Sign in to the CloudFront dashboard

- Select the CloudFront Distribution for which you want to configure the custom error page
- Select the "Error Pages" tab
- Find and select the "Error Pages" tab
- Create custom error page
- Click "Create custom error response" button


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ytkvjj69x9dsdcyjexet.png)

You can configure a custom error page with the following settings.

   - HTTP error code > 403 Forbidden
   - Error caching minimum TTL: 60
   - Customize error response: Yes
   - Response page path: /error.html
   - HTTP Response code: 200 OK
   - Select Create custom error response

- With these settings, when your site encounters an HTTP error > 403 Forbidden, it will display a custom error page previously configured and cache it for at least 60 seconds. Customers visiting your website will receive a custom error response with the path /error.html and the HTTP response code 200 OK.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nchqbgkjv0qe8679raz6.png)

Create a successful custom error response.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u23igdorvxoou4bfglax.png)

Test your custom error page by requesting a random page from CloudFront. It may take a few minutes for the update to deliver and propagate to the Edge locations. Make sure you use a different random value than in the previous test, or else you will get the same cached version as when you tested in the last 5 minutes.

- To check custom error page, follow these steps:

  - Open a web browser and visit a random page from CloudFront.
  - Wait a few minutes for CloudFront to update and spread the distribution.
  - Enter a random value different from the previous test.
  - Get HTTP > 403 Forbidden error messages from CloudFront.
  - Check if custom error page is displayed or not. If the custom error page is displayed, the configuration is successful.

- If you're still getting the default CloudFront error message, double check your custom error page configuration and make sure you've saved the changes. You should also check that your values ​​match the required settings.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o07uw1jcaqpnms4vr6ms.png)

Create a new custom error page to display when CloudFront cannot connect to the source. Use the following settings:

   - HTTP error code > 504 Gateway Timeout
   - Error caching minimum TTL: 5
   - Customize error response: Yes
   - Response page path: /error.html
   - HTTP Response code: 200 OK
   - Select Create custom error response


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syykv0tccxyzo6npdz7q.png)

Finish creating 2 Error pages.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pcc3zf58xdiaud9lkgbe.png)

Change Inbound rule of Security group

- Access to EC2 Console.
- At the EC2 Console interface, select Security Groups in the left panel.
- Select Security Group containing Inbound rule to access EC2 instance running Nodejs API.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezpi7o4ps6ogj1sbhntt.png)

Edit Inbound rule for **HTTP** from **0.0.0.0/0** to **MyIP**
- Select the Save Rules button to save the changes made.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d80qd681nu2zgt8jqdcj.png)

Edit Security group successfully.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dzuvu87hy12fqiv0b30e.png)

Open a web browser and enter the CloudFront URL of the index.html page in the address bar.
- Press Enter to access the website.
- Check if the website is working properly or not.
- You will see the interface as shown


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ns5tt0ajl5urvtz1wyna.png)


#### 3. Create Origin Group 

In this section, you will configure an Origin Group to provide rerouting in the event of a problem. You can associate an Origin Group with a caching behavior so that requests are routed from the primary source to the secondary source for high availability.

Go to the S3 dashboard, create a new S3 bucket in a different area
- Give the S3 bucket a unique name, remember that the S3 bucket name is globally unique, so add a personalization suffix, for example:

```
cloudfrontlab-s3bucket-secondary-<YourNameHere>
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ogkkwhs9pjn2dm9sb5k4.png)

Select **Create bucket**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u8scdvszsrvsicb1l5fk.png)

Create a secondary-index.html file on your computer with the HTML content below:


```
<html lang="en">
  <body>
    <h1>CloudFront Lab</h1>
    <strong>Hi, this is a page from my secondary Origin! We now support Origin group and failover!</strong>
  </body>
</html>

```

- Open a web browser and log in to the S3 console.
   - Select the name of the S3 bucket that you want to upload the file to.
   - Click the "Upload" button in the upper right corner of the web page.
   - Select the secondary-index.html file from your computer by clicking the "Add files" button or dragging and dropping the file into the upload area.
   - Click the "Upload" button to upload your secondary-index.html file to S3.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jrox0pkmft9ot76gr66.png)

Upload successful.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jjz7jmr2icoi1eye11md.png)

Go to your AWS account and select the CloudFront service.
   - Find and select the CloudFront Distribution for which you want to configure the origin group.
   - Create a new origin by selecting the "Create Origin" option


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rn79lxctijeppejbqwdx.png)

Choose your origin domain name and select the new S3 bucket containing the secondary-index.html file.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iz41f2ca0633klf6f3et.png)

Set up access to the S3 bucket by selecting "Yes, use OAI" and selecting "Select" to select the OAI you created earlier.
   - Update the bucket policy by selecting "Yes, update the bucket policy".
   - Select **Create origin**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kf9sprj4z5rmfq7ka9xd.png)

Create origin successfully. Click the Create Origin Group button to create a new Origin Group.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nkh6b2vi7hxgxqj2s5al.png)

Make origin group configuration. Select the source from the drop-down list and click the Add button to add the source to the Origin Group.
   - Use cloudfrontlab-s3bucket-* as primary origin
   - And cloudfrontlab-s3bucket-secondary-<YourNameHere> as secondary origin
   - For failover criteria, select 403 Forbidden and 404 Not Found.
   - Click the Create origin group button to finish adding the source to the Origin Group.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0dq42b8cxxaclu7tvnk.png)

Once done, you have successfully added the source to Origin Group on CloudFront. When the primary source fails, CloudFront automatically redirects to the second source to ensure service continuity.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/818yjuk5p21zkhf93x0d.png)

Edit default behavior on CloudFront to use new Origin Group

    - Select the Behaviors tab
    - Select Default(*) and click the Edit button to edit the default behavior of the distribution.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n24dqbz8sfqa6u63cdy0.png)

Select the Origin Group created in the previous step.
- Click the Save changes button to save the changes.
- Once done, CloudFront will use the new Origin Group as the source when accessing the distribution. You can test failover functionality by trying to visit the website and temporarily disconnecting from the network to check if CloudFront redirects to the second source.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n3iq6xncrige1ak67he1.png)

Once the distribution status is changed to Deployed, you can request the secondary-index.html site from CloudFront. If CloudFront is working correctly, you should see the second S3 origin serving your request.
    - Open a web browser and access the URL of the CloudFront distribution.
    - Change the URL from /index.html to /secondary-index.html to request the site from the second S3 origin.
    - Check if the web page has been uploaded from the second S3 origin. If the web page is properly uploaded and displayed, it is an indication that CloudFront is working correctly and redirects to the second S3 origin when necessary.
    - Note: If the site is not uploaded or displayed incorrectly, double check your settings to make sure it is properly configured and working as expected.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sohvlhlnwh15xdgwymkz.png)

### The following sections

[Get started with CloudFront - Part 1: CloudFront Distribution](https://dev.to/aws-builders/get-started-with-cloudfront-cloudfront-distribution-2n1m)

[Get started with CloudFront - Part 2: Distribution Invalidations](https://dev.to/aws-builders/get-started-with-cloudfront-part-2-distribution-invalidations-2d4)

[Get started with CloudFront - Part 3: Response Headers and Cache Behavior](https://dev.to/aws-builders/get-started-with-cloudfront-part-3-response-headersand-cache-behavior-2n5e)

[Get started with CloudFront - Part 4: Lambda@Edge function](https://dev.to/aws-builders/get-started-with-cloudfront-part-4-lambdaedge-function-4cbh)