CloudFront
AWS CloudFront is a content delivery network (CDN) service which accelerates the delivery of web content, including images, videos, and dynamic assets, to users worldwide. By distributing content across a global network of edge locations, it reduces latency, improves load times, and enhances the user experience. CloudFront also offers security features, such as DDoS protection and access control, making it a versatile solution for both static and dynamic web applications. It integrates seamlessly with other AWS services and provides detailed analytics for monitoring content delivery performance.
- What options of HTTPS are available in AWS CloudFront?
- Between clients and CloudFront as well as between CloudFront and origin via - Viewer to Cloudfront , Cloudfront to Origin
- IAM users can't create CloudFront key pairs. You must log in using root credentials to create key pairs.
- Cookie forwarding: By default, CloudFront doesn't include cookies when processing requests and responses. You can configure CloudFront to forward to your origin some or all of the cookies in viewer requests, and to cache separate versions of your objects based on the cookie values that it forwards.
- Header forwarding: It helps to forward the request headers to the origin server. Because some headers may contain critical information that your server needs to generate a response.
- For example, suppose you’re using CloudFront to serve a web application that requires user authentication. In that case, you’ll need to forward the
Authorization
header to your server to verify the user’s identity. Similarly, if you’re serving content in different languages, you’ll need to forward theAccept-Language
header to your server to determine the appropriate language for the response.
- For example, suppose you’re using CloudFront to serve a web application that requires user authentication. In that case, you’ll need to forward the
- When CloudFront returns HTTP 4xx and 5xx status codes response for an object - which means the object(s) requested were not found on the origin server and the origin server generated the 404 error, which is returned by CloudFront
Behaviours
Origin failover
How origin failover works:
via - Link
- CloudFront fails over to the secondary origin only when the HTTP method of the viewer request is
GET
,HEAD
orOPTIONS
. CloudFront does not failover when the viewer sends a different HTTP method (for example POST, PUT, and so on). - CloudFront routes all incoming requests to the primary origin, even when a previous request failed over to the secondary origin. CloudFront only sends requests to the secondary origin after a request to the primary origin fails.
Features
Reports
Amazon CloudFront includes a variety of reports that the Administrator can use to see usage and activity that is occurring in the CloudFront distributions.
- Popular Objects Report can determine what objects are frequently being accessed and get statistics on those objects.
- Usage Reports tells you the number of HTTP and HTTPS requests that CloudFront responds to from edge locations in selected regions.
- Viewers Reports can determine the locations of the viewers that access your content most frequently.
Reference:
Signed URLs
Source: CloudFront Signed URLs / Cookies and S3 Presigned URLs
-
In your CloudFront distribution, specify one or more trusted key groups, which contain the public keys that CloudFront can use to verify the URL signature. You use the corresponding private keys to sign the URLs.
-
Develop your application to determine whether a user should have access to your content and to create signed URLs for the files or parts of your application that you want to restrict access to.
-
A user requests a file for which you want to require signed URLs. Your application verifies that the user is entitled to access the file: they've signed in, they've paid for access to the content, or they've met some other requirement for access.
-
Your application creates and returns a signed URL to the user. The signed URL allows the user to download or stream the content.
Signed Cookies
Source: CloudFront Signed URLs / Cookies and S3 Presigned URLs
Origin Shield
CloudFront Origin Shield provides a centralized caching layer that sits in front of your origin to help increase CloudFront’s cache hit ratio and collapse simultaneous requests for the same object coming across multiple regions. As a general best practice, you should always choose the Origin Shield Region that is closest to your origin.
When enabled, all origin fetches coming from any CloudFront Point of Presence or Regional Edge Cache will now be routed through the Origin Shield location for a final cache check. Any content not already held in the Origin Shield location will then benefit from central request consolidation so that as little as one request goes to the origin.
- Before implement origin shield
- After implement origin shield
Restricting access to files on custom origins
Reference: Restricting access to files on custom origins
If you use a custom origin, you can optionally set up custom headers to restrict access. For CloudFront to get your files from a custom origin, the files must be accessible by CloudFront using a standard HTTP (or HTTPS) request. But by using custom headers, you can further restrict access to your content so that users can access it only through CloudFront, not directly. This step isn't required to use signed URLs, but we recommend it.
To require that users access content through CloudFront, change the following settings in your CloudFront distributions:
- Origin Custom Headers
- Viewer Protocol Policy
- Origin Protocol Policy
Origin Custom Headers
Configure CloudFront to forward custom headers to your origin. See Configuring CloudFront to add custom headers to origin requests.
- If you want CloudFront to cache different versions of your objects based on the device that a user is using to view your content, use
User-Agent
header. You can create values like CloudFront-Is-Desktop-Viewer, CloudFront-Is-Mobile-Viewer, etc Based on the value of theUser-Agent
header, CloudFront sets the value of these headers to true or false before forwarding the request to your origin. If a device falls into more than one category, more than one value might be true. - In S3 you can set an IAM policy like:
{
"Version": "2008-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::<S3バケット>/*",
"Condition": {
"StringEquals": {
"aws:UserAgent": "Amazon CloudFront <任意文字列>"
}
}
}
]
}
Viewer Protocol Policy
Configure your distribution to require viewers to use HTTPS to access CloudFront. See Viewer protocol policy.
Origin Protocol Policy
Configure your distribution to require CloudFront to use the same protocol as viewers to forward requests to the origin. See Protocol (custom origins only).
After you've made these changes, update your application on your custom origin to only accept requests that include the custom headers that you've configured CloudFront to send.
The combination of Viewer Protocol Policy and Origin Protocol Policy ensure that the custom headers are encrypted in transit. However, we recommend that you periodically do the following to rotate the custom headers that CloudFront forwards to your origin:
- Update your CloudFront distribution to begin forwarding a new header to your custom origin.
- Update your application to accept the new header as confirmation that the request is coming from CloudFront.
- When requests no longer include the header that you're replacing, update your application to no longer accept the old header as confirmation that the request is coming from CloudFront.
Cloudfront signers
Each signer that you use to create CloudFront signed URLs or signed cookies must have a public-private key pair. The signer uses its * private key to sign the URL or cookies*, and CloudFront uses the * public key to verify the signature*.
Public Key & Private Key
When you create signed URLs or signed cookies, you use the private key from the signer's key pair to sign a portion of the URL or the cookie. When someone requests a restricted file, CloudFront compares the signature in the URL or cookie with the unsigned URL or cookie, to verify that it hasn't been tampered with. CloudFront also verifies that the URL or cookie is valid, meaning, for example, that the expiration date and time haven't passed.
CloudFront key groups
When you use the root user to manage CloudFront key pairs, you can only have up to two active CloudFront key pairs per AWS account
Whereas, with CloudFront key groups, you can associate a higher number of public keys with your CloudFront distribution, giving you more flexibility in how you use and manage the public keys. By default, you can associate up to four key groups with a single distribution, and you can have up to five public keys in a key group.
Reference: Specifying the signers that can create signed URLs and signed cookies
Settings
Improve performance
You can improve performance by increasing the proportion of your viewer requests that are served from CloudFront edge caches instead of going to your origin servers for content; that is, by improving the cache hit ratio for your distribution.
This can be done by doing any of the following:
- Increase the TTL of your objects
- Configure the distribution to forward only the required query string parameters, cookies, or request headers for which your origin will return unique objects.
- Remove Accept-Encoding header when compression is not needed
- Serving Media Content by using HTTP
Serving Static and Dynamic content
Amazon CloudFront is commonly utilized for distributing static content stored in an Amazon S3 bucket, including images, videos, and other objects. However, it offers more than that. You can leverage Amazon CloudFront to distribute dynamic content from web applications built on platforms like Ruby on Rails or PHP.
By doing so, you can take advantage of AWS's widespread network infrastructure, ensuring fast and reliable delivery of your dynamic content to users around the world.
If you want to split between static and dynamic content you would create an origin for each type of content (static & dynamic) within the same distribution. The origins can be S3 or web servers (aws instances), etc. CloudFront can serve both static and dynamic content by following these steps:
- Serving Static Content
- Upload your static files (e.g., HTML, CSS, JavaScript) to an Amazon S3 bucket.
- Configure the bucket for static website hosting, specifying the index and error documents.
- Create a CloudFront distribution, setting the S3 bucket as the origin and configuring caching settings.
- Associate a domain name with the CloudFront distribution using a custom SSL certificate if needed.
- Update DNS records to point to the CloudFront distribution's domain name.
- Serving Dynamic Content
- Set up a web server (e.g., EC2 instance) or an application server (e.g., Lambda@Edge) to generate dynamic content.
- Configure the server to handle requests and generate appropriate responses for dynamic content.
- Create an Application Load Balancer (ALB) or an API Gateway and integrate it with your server.
- Set up the ALB or API Gateway as the origin for your CloudFront distribution.
- Configure caching behaviors and TTLs for dynamic content based on your application's requirements.
- Associate a domain name with the CloudFront distribution and update DNS records accordingly.
Futher reading:
- What is the difference between static and dynamic content?
- Serving Dynamic Websites with Amazon CloudFront
- StackOverflow - How AWS Cloudfront works for both static website and dynamic website
Trouble shooting
Invalidating cache
If you need to remove a file from CloudFront edge caches before it expires, you can do one of the following:
- Invalidate the file from edge caches. The next time a viewer requests the file, CloudFront returns to the origin to fetch the latest version of the file.
- Use file versioning to serve a different version of the file that has a different name. For more information, see Updating existing files using versioned file names. For example, instead of naming a graphic file image.jpg, you might call it image_1.jpg. When you want to start serving a new version of the file, you'd name the new file image_2.jpg, and you'd update the links in your web application or website to point to image_2.jpg.
Error messages
The authorization header is malformed; the region '<AWS Region>' is wrong; expecting '<AWS Region>'
- This error indicates the configured Amazon S3 bucket has been moved from one AWS Region to the other. That is, deleted from one AWS Region and created with the same name in another. To fix this error, update your CloudFront distribution so that it finds the S3 bucket in the bucket's current AWS Region