id
stringlengths 8
78
| source
stringclasses 743
values | chunk_id
int64 1
5.05k
| text
stringlengths 593
49.7k
|
---|---|---|---|
AmazonCloudFront_DevGuide-050 | AmazonCloudFront_DevGuide.pdf | 50 | • You're using a CloudFront origin access identity (OAI) to restrict access to the bucket. • You move the bucket to an Amazon S3 Region that requires Signature Version 4 for authentication. When you're using OAIs, CloudFront uses the Region (among other values) to calculate the signature that it uses to request objects from your bucket. For more information about OAIs, see the section called “Use an origin access identity (legacy, not recommended)”. For a list of AWS Regions that support Signature Version 2, see Signature Version 2 signing process in the Amazon Web Services General Reference. To force a faster update to CloudFront's records, you can update your CloudFront distribution, for example, by updating the Description field on the General tab in the CloudFront console. When you update a distribution, CloudFront immediately checks the Region that your bucket is in. Propagation of the change to all edge locations should take only a few minutes. Use a MediaStore container or a MediaPackage channel To stream video using CloudFront, you can set up an Amazon S3 bucket that is configured as a MediaStore container, or create a channel and endpoints with MediaPackage. Then you create and configure a distribution in CloudFront to stream the video. For more information and step-by-step instructions, see the following topics: • the section called “Serve video by using AWS Elemental MediaStore as the origin” • the section called “Serve live video formatted with AWS Elemental MediaPackage” Use an Application Load Balancer To prevent your application from being accessible on the public internet, you can use your Application Load Balancer with a VPC origin. For more information, see Restrict access with VPC origins. Use a MediaStore container or a MediaPackage channel 121 Amazon CloudFront Developer Guide Alternatively, if your origin is one or more HTTP(S) servers (web servers) hosted on one or more Amazon EC2 instances, you can choose to use an internet-facing Application Load Balancer to distribute traffic to the instances. An internet-facing load balancer has a publicly resolvable DNS name and routes requests from clients to targets over the internet. For more information about using an Application Load Balancer as your origin for CloudFront, including how to make sure that viewers can only access your web servers through CloudFront and not by accessing the load balancer directly, see the section called “Restrict access to Application Load Balancers”. Use a Lambda function URL A Lambda function URL is a dedicated HTTPS endpoint for a Lambda function. You can use a Lambda function URL to build a serverless web application entirely within Lambda. You can invoke the Lambda web application directly through the function URL, with no need to integrate with API Gateway or an Application Load Balancer. If you build a serverless web application by using Lambda functions with function URLs, you can add CloudFront to get the following benefits: • Speed up your application by caching content closer to viewers • Use a custom domain name for your web application • Route different URL paths to different Lambda functions using CloudFront cache behaviors • Block specific requests using CloudFront geographic restrictions or AWS WAF (or both) • Use AWS WAF with CloudFront to help protect your application from malicious bots, help prevent common application exploits, and enhance protection from DDoS attacks To use a Lambda function URL as the origin for a CloudFront distribution, specify the full domain name of the Lambda function URL as the origin domain. A Lambda function URL domain name uses the following format: function-URL-ID.lambda-url.AWS-Region.on.aws When you use a Lambda function URL as the origin for a CloudFront distribution, the function URL must be publicly accessible. To do so, use one of the following options: • If you use origin access control (OAC), the AuthType parameter of the Lambda function URL must use the AWS_IAM value and allow the lambda:InvokeFunctionUrl permission in a Use a Lambda function URL 122 Amazon CloudFront Developer Guide resource-based policy. For more information about using Lambda function URLs for OAC, see Restrict access to an AWS Lambda function URL origin. • If you don't use OAC, you can set the AuthType parameter of the function URL to NONE and allow the lambda:InvokeFunctionUrl permission in a resource-based policy. You can also add a custom origin header to the requests that CloudFront sends to the origin, and write function code to return an error response if the header isn't present in the request. This helps to make sure that users can only access your web application through CloudFront, not directly using the Lambda function URL. For more information about Lambda function URLs, see the following topics in the AWS Lambda Developer Guide: • Lambda function URLs – A general overview of the Lambda function URLs feature • Invoking Lambda function URLs – Includes details about the request and |
AmazonCloudFront_DevGuide-051 | AmazonCloudFront_DevGuide.pdf | 51 | policy. You can also add a custom origin header to the requests that CloudFront sends to the origin, and write function code to return an error response if the header isn't present in the request. This helps to make sure that users can only access your web application through CloudFront, not directly using the Lambda function URL. For more information about Lambda function URLs, see the following topics in the AWS Lambda Developer Guide: • Lambda function URLs – A general overview of the Lambda function URLs feature • Invoking Lambda function URLs – Includes details about the request and response payloads to use for coding your serverless web application • Security and auth model for Lambda function URLs – Includes details about the Lambda auth types Use Amazon EC2 (or another custom origin) A custom origin is an HTTP(S) web server with a publicly resolvable DNS name that routes requests from clients to targets over the internet. The HTTP(S) server can be hosted on AWS–for example, an Amazon EC2 instance–or hosted somewhere else. An Amazon S3 origin configured as a website endpoint is also considered a custom origin. For more information, see the section called “Use an Amazon S3 bucket that's configured as a website endpoint”. When you use your own HTTP server as a custom origin, you specify the DNS name of the server, along with the HTTP and HTTPS ports and the protocol that you want CloudFront to use when fetching objects from your origin. Most CloudFront features are supported when you use a custom origin with the exception of private content. Although you can use a signed URL to distribute content from a custom origin, for CloudFront to access the custom origin, the origin must remain publicly accessible. For more information, see the section called “Restrict content with signed URLs and signed cookies”. Use Amazon EC2 (or another custom origin) 123 Amazon CloudFront Developer Guide To prevent your application from being accessible on the public internet, you can use your EC2 instance with a VPC origin. For more information, see Restrict access with VPC origins. Follow these guidelines for using Amazon EC2 instances and other custom origins with CloudFront. • Host and serve the same content on all servers that are serving content for the same CloudFront origin. For more information, see the section called “Origin settings” in the the section called “Distribution settings” topic. • Log the X-Amz-Cf-Id header entries on all servers in case you need Support or CloudFront to use this value for debugging. • Restrict requests to the HTTP and HTTPS ports that your custom origin listens on. • Synchronize the clocks of all servers in your implementation. Note that CloudFront uses Coordinated Universal Time (UTC) for signed URLs and signed cookies, for logs, and reports. In addition, if you monitor CloudFront activity using CloudWatch metrics, note that CloudWatch also uses UTC. • Use redundant servers to handle failures. • For information about using a custom origin to serve private content, see the section called “Restrict access to files on custom origins”. • For information about request and response behavior and about supported HTTP status codes, see Request and response behavior. If you use Amazon EC2 for a custom origin, we recommend that you do the following: • Use an Amazon Machine Image that automatically installs the software for a web server. For more information, see the Amazon EC2 documentation. • Use an Elastic Load Balancing load balancer to handle traffic across multiple Amazon EC2 instances and to isolate your application from changes to Amazon EC2 instances. For example, if you use a load balancer, you can add and delete Amazon EC2 instances without changing your application. For more information, see the Elastic Load Balancing documentation. • When you create your CloudFront distribution, specify the URL of the load balancer for the domain name of your origin server. For more information, see the section called “Create a distribution”. Use Amazon EC2 (or another custom origin) 124 Amazon CloudFront Developer Guide Use CloudFront origin groups You can specify an origin group for your CloudFront origin if, for example, you want to configure origin failover for scenarios when you need high availability. Use origin failover to designate a primary origin for CloudFront plus a second origin that CloudFront automatically switches to when the primary origin returns specific HTTP status code failure responses. For more information, including the steps for setting up an origin group, see the section called “Increase availability with origin failover”. Use Amazon API Gateway You can use API Gateway as a custom origin for your CloudFront distribution. For more information, see the following topics: • Securing Amazon API Gateway with secure ciphers using Amazon CloudFront AWS blog post • How do I set up API Gateway with my own CloudFront distribution? |
AmazonCloudFront_DevGuide-052 | AmazonCloudFront_DevGuide.pdf | 52 | failover to designate a primary origin for CloudFront plus a second origin that CloudFront automatically switches to when the primary origin returns specific HTTP status code failure responses. For more information, including the steps for setting up an origin group, see the section called “Increase availability with origin failover”. Use Amazon API Gateway You can use API Gateway as a custom origin for your CloudFront distribution. For more information, see the following topics: • Securing Amazon API Gateway with secure ciphers using Amazon CloudFront AWS blog post • How do I set up API Gateway with my own CloudFront distribution? AWS re:Post Use CloudFront continuous deployment to safely test CDN configuration changes With Amazon CloudFront continuous deployment you can safely deploy changes to your CDN configuration by testing first with a subset of production traffic. You can use a staging distribution and a continuous deployment policy to send some traffic from real (production) viewers to the new CDN configuration and validate that it works as expected. You can monitor the performance of the new configuration in real time, and promote the new configuration to serve all traffic via the primary distribution when you're ready. The following diagram shows the benefit of using CloudFront continuous deployment. Without it, you would have to test CDN configuration changes with simulated traffic. With continuous deployment you can test the changes with a subset of production traffic, then promote the changes to the primary distribution when you're ready. Use CloudFront origin groups 125 Amazon CloudFront Developer Guide Use continuous deployment to safely test changes 126 Amazon CloudFront Developer Guide Learn more about working with continuous deployment in the following topics. Topics • CloudFront continuous deployment workflow • Work with a staging distribution and continuous deployment policy • Monitor a staging distribution • Learn how continuous deployment works • Quotas and other considerations for continuous deployment CloudFront continuous deployment workflow The following high-level workflow explains how to safely test and deploy configuration changes with CloudFront continuous deployment. 1. Choose the distribution that you want to use as the primary distribution. The primary distribution is one that currently serves production traffic. 2. From the primary distribution, create a staging distribution. A staging distribution starts as a copy of the primary distribution. 3. Create a traffic configuration inside a continuous deployment policy, and attach it to the primary distribution. This determines how CloudFront routes traffic to the staging distribution. For more information about routing requests to a staging distribution, see the section called “Route requests to the staging distribution”. 4. Update the configuration of the staging distribution. For more information about the settings that you can update, see the section called “Update primary and staging distributions”. 5. Monitor the staging distribution to determine whether the configuration changes perform as expected. For more information about monitoring a staging distribution, see the section called “Monitor a staging distribution”. As you monitor the staging distribution, you can: • Update the configuration of the staging distribution again, to continue testing configuration changes. • Update the continuous deployment policy (traffic configuration) to send more or less traffic to the staging distribution. 6. When you're satisfied with the performance of the staging distribution, promote the staging distribution's configuration to the primary distribution, which copies the staging distribution's CloudFront continuous deployment workflow 127 Amazon CloudFront Developer Guide configuration to the primary distribution. This also disables the continuous deployment policy which means that CloudFront routes all traffic to the primary distribution. You can build automation that monitors the performance of the staging distribution (step 5) and promotes the configuration automatically (step 6) when certain criteria are met. After you promote a configuration, you can reuse the same staging distribution the next time you want to test a configuration change. For more information about working with staging distributions and continuous deployment policies in the CloudFront console, the AWS CLI, or the CloudFront API, see the following section. Work with a staging distribution and continuous deployment policy You can create, update, and modify staging distributions and continuous deployment policies in the CloudFront console, with the AWS Command Line Interface (AWS CLI), or with the CloudFront API. Create a staging distribution with a continuous deployment policy The following procedures show you how to create a staging distribution with a continuous deployment policy. Console You can create a staging distribution with a continuous deployment policy by using the AWS Management Console. To create a staging distribution and continuous deployment policy (console) 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions. 3. Choose the distribution that you want to use as the primary distribution. The primary distribution is one that currently serves production traffic, the one from which you will create the staging distribution. 4. In the |
AmazonCloudFront_DevGuide-053 | AmazonCloudFront_DevGuide.pdf | 53 | show you how to create a staging distribution with a continuous deployment policy. Console You can create a staging distribution with a continuous deployment policy by using the AWS Management Console. To create a staging distribution and continuous deployment policy (console) 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions. 3. Choose the distribution that you want to use as the primary distribution. The primary distribution is one that currently serves production traffic, the one from which you will create the staging distribution. 4. In the Continuous deployment section, choose Create staging distribution. This opens the Create staging distribution wizard. Work with a staging distribution and continuous deployment policy 128 Amazon CloudFront Developer Guide 5. In the Create staging distribution wizard, do the following: a. (Optional) Type a description for the staging distribution. b. Choose Next. c. Modify the configuration of the staging distribution. For more information about the settings that you can update, see the section called “Update primary and staging distributions”. When you are finished modifying the staging distribution's configuration, choose Next. d. Use the console to specify the Traffic configuration. This determines how CloudFront routes traffic to the staging distribution. (CloudFront stores the traffic configuration in a continuous deployment policy.) For more information about the options in a Traffic configuration, see the section called “Route requests to the staging distribution”. When you are finished with the Traffic configuration, choose Next. e. Review the configuration for the staging distribution, including the traffic configuration, then choose Create staging distribution. When you finish the Create staging distribution wizard in the CloudFront console, CloudFront does the following: • Creates a staging distribution with the settings that you specified (in step 5c) • Creates a continuous deployment policy with the traffic configuration that you specified (in step 5d) • Attaches the continuous deployment policy to the primary distribution that you created the staging distribution from When the primary distribution's configuration, with the attached continuous deployment policy, deploys to edge locations, CloudFront begins sending the specified portion of traffic to the staging distribution based on the traffic configuration. CLI To create a staging distribution and a continuous deployment policy with the AWS CLI, use the following procedures. Work with a staging distribution and continuous deployment policy 129 Amazon CloudFront Developer Guide To create a staging distribution (CLI) 1. Use the aws cloudfront get-distribution and grep commands together to get the ETag value of the distribution that you want to use as the primary distribution. The primary distribution is one that currently serves production traffic, from which you will create the staging distribution. The following command shows an example. In the following example, replace primary_distribution_ID with the ID of the primary distribution. aws cloudfront get-distribution --id primary_distribution_ID | grep 'ETag' Copy the ETag value because you need it for the following step. 2. Use the aws cloudfront copy-distribution command to create a staging distribution. The following example command uses escape characters (\) and line breaks for readability, but you should omit these from the command. In the following example command: • Replace primary_distribution_ID with the ID of the primary distribution. • Replace primary_distribution_ETag with the ETag value of the primary distribution (that you got in the previous step). • (Optional) Replace CLI_example with the desired caller reference ID. aws cloudfront copy-distribution --primary-distribution- id primary_distribution_ID \ --if-match primary_distribution_ETag \ --staging \ --caller-reference 'CLI_example' The command's output shows information about the staging distribution and its configuration. Copy the staging distribution's CloudFront domain name because you need it for a following step. Work with a staging distribution and continuous deployment policy 130 Amazon CloudFront Developer Guide To create a continuous deployment policy (CLI with input file) 1. Use the following command to create file named continuous-deployment- policy.yaml that contains all of the input parameters for the create-continuous- deployment-policy command. The following command uses escape characters (\) and line breaks for readability, but you should omit these from the command. aws cloudfront create-continuous-deployment-policy --generate-cli-skeleton yaml- input \ > continuous-deployment- policy.yaml 2. Open the file named continuous-deployment-policy.yaml that you just created. Edit the file to specify the continuous deployment policy settings that you want, then save the file. When you edit the file: • In the StagingDistributionDnsNames section: • Change the value of Quantity to 1. • For Items, paste the CloudFront domain name of the staging distribution (that you saved from a previous step). • In the TrafficConfig section: • Choose a Type, either SingleWeight or SingleHeader. • Remove the settings for the other type. For example, if you want a weight- based traffic configuration, set Type to SingleWeight and then remove the SingleHeaderConfig settings. • To use a weight-based traffic configuration, set the value of Weight to a decimal number between .01 (one |
AmazonCloudFront_DevGuide-054 | AmazonCloudFront_DevGuide.pdf | 54 | save the file. When you edit the file: • In the StagingDistributionDnsNames section: • Change the value of Quantity to 1. • For Items, paste the CloudFront domain name of the staging distribution (that you saved from a previous step). • In the TrafficConfig section: • Choose a Type, either SingleWeight or SingleHeader. • Remove the settings for the other type. For example, if you want a weight- based traffic configuration, set Type to SingleWeight and then remove the SingleHeaderConfig settings. • To use a weight-based traffic configuration, set the value of Weight to a decimal number between .01 (one percent) and .15 (fifteen percent). For more information about the options in TrafficConfig, see the section called “Route requests to the staging distribution” and the section called “Session stickiness for weight-based configurations”. 3. Use the following command to create the continuous deployment policy using input parameters from the continuous-deployment-policy.yaml file. Work with a staging distribution and continuous deployment policy 131 Amazon CloudFront Developer Guide aws cloudfront create-continuous-deployment-policy --cli-input-yaml file:// continuous-deployment-policy.yaml Copy the Id value in the command's output. This is the continuous deployment policy ID, and you need it in a following step. To attach a continuous deployment policy to a primary distribution (CLI with input file) 1. Use the following command to save the primary distribution's configuration to a file named primary-distribution.yaml. Replace primary_distribution_ID with the primary distribution's ID. aws cloudfront get-distribution-config --id primary_distribution_ID --output yaml > primary-distribution.yaml 2. Open the file named primary-distribution.yaml that you just created. Edit the file, making the following changes: • Paste the continuous deployment policy ID (that you copied from a previous step) into the ContinuousDeploymentPolicyId field. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the primary distribution to use the continuous deployment policy. Replace primary_distribution_ID with the primary distribution's ID. aws cloudfront update-distribution --id primary_distribution_ID --cli-input-yaml file://primary-distribution.yaml When the primary distribution's configuration, with the attached continuous deployment policy, deploys to edge locations, CloudFront begins sending the specified portion of traffic to the staging distribution based on the traffic configuration. Work with a staging distribution and continuous deployment policy 132 Amazon CloudFront API Developer Guide To create a staging distribution and continuous deployment policy with the CloudFront API, use the following API operations: • CopyDistribution • CreateContinuousDeploymentPolicy For more information about the fields that you specify in these API calls, see the following: • the section called “Route requests to the staging distribution” • the section called “Session stickiness for weight-based configurations” • The API reference documentation for your AWS SDK or other API client After you create a staging distribution and a continuous deployment policy, use UpdateDistribution (on the primary distribution) to attach the continuous deployment policy to the primary distribution. Update a staging distribution The following procedures show you how to update a staging distribution with a continuous deployment policy. Console You can update certain configurations for both the primary and staging distributions. For more information, see Update primary and staging distributions. To update a staging distribution (console) 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions. 3. Choose the primary distribution. This is the distribution that currently serves production traffic, the one from which you created the staging distribution. 4. Choose View staging distribution. Work with a staging distribution and continuous deployment policy 133 Amazon CloudFront Developer Guide 5. Use the console to modify the configuration of the staging distribution. For more information about the settings that you can update, see the section called “Update primary and staging distributions”. As soon as the staging distribution's configuration deploys to edge locations it takes effect for incoming traffic that's routed to the staging distribution. CLI To update a staging distribution (CLI with input file) 1. Use the following command to save the staging distribution's configuration to a file named staging-distribution.yaml. Replace staging_distribution_ID with the staging distribution's ID. aws cloudfront get-distribution-config --id staging_distribution_ID --output yaml > staging-distribution.yaml 2. Open the file named staging-distribution.yaml that you just created. Edit the file, making the following changes: • Modify the configuration of the staging distribution. For more information about the settings that you can update, see the section called “Update primary and staging distributions”. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the staging distribution's configuration. Replace staging_distribution_ID with the staging distribution's ID. aws cloudfront update-distribution --id staging_distribution_ID --cli-input-yaml file://staging-distribution.yaml As soon as the staging distribution's configuration deploys to edge locations it takes effect for incoming traffic that's routed to the staging distribution. Work with a staging distribution and continuous deployment policy 134 Amazon CloudFront API Developer Guide To update the configuration of a staging distribution, use |
AmazonCloudFront_DevGuide-055 | AmazonCloudFront_DevGuide.pdf | 55 | update, see the section called “Update primary and staging distributions”. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the staging distribution's configuration. Replace staging_distribution_ID with the staging distribution's ID. aws cloudfront update-distribution --id staging_distribution_ID --cli-input-yaml file://staging-distribution.yaml As soon as the staging distribution's configuration deploys to edge locations it takes effect for incoming traffic that's routed to the staging distribution. Work with a staging distribution and continuous deployment policy 134 Amazon CloudFront API Developer Guide To update the configuration of a staging distribution, use UpdateDistribution (on the staging distribution) to modify the configuration of the staging distribution. For more information about the settings that you can update, see the section called “Update primary and staging distributions”. Update a continuous deployment policy The following procedures show you how to update a continuous deployment policy. Console You can update your distribution's traffic configuration by updating the continuous deployment policy. To update a continuous deployment policy (console) 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions. 3. Choose the primary distribution. This is the distribution that currently serves production traffic, the one from which you created the staging distribution. 4. In the Continuous deployment section, choose Edit policy. 5. Modify the traffic configuration in the continuous deployment policy. When you are finished, choose Save changes. When the primary distribution's configuration with the updated continuous deployment policy deploys to edge locations, CloudFront begins sending traffic to the staging distribution based on the updated traffic configuration. CLI To update a continuous deployment policy (CLI with input file) 1. Use the following command to save the continuous deployment policy's configuration to a file named continuous-deployment-policy.yaml. Replace continuous_deployment_policy_ID with the continuous deployment policy's ID. The following command uses escape characters (\) and line breaks for readability, but you should omit these from the command. Work with a staging distribution and continuous deployment policy 135 Amazon CloudFront Developer Guide aws cloudfront get-continuous-deployment-policy-config -- id continuous_deployment_policy_ID \ --output yaml > continuous-deployment-policy.yaml 2. Open the file named continuous-deployment-policy.yaml that you just created. Edit the file, making the following changes: • Modify the configuration of the continuous deployment policy as desired. For example, you can change from using a header-based to a weight-based traffic configuration, or you can change the percentage of traffic (weight) for a weight-based configuration. For more information, see the section called “Route requests to the staging distribution” and the section called “Session stickiness for weight-based configurations”. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the continuous deployment policy. Replace continuous_deployment_policy_ID with the continuous deployment policy's ID. The following command uses escape characters (\) and line breaks for readability, but you should omit these from the command. aws cloudfront update-continuous-deployment-policy -- id continuous_deployment_policy_ID \ --cli-input-yaml file:// continuous-deployment-policy.yaml When the primary distribution's configuration with the updated continuous deployment policy deploys to edge locations, CloudFront begins sending traffic to the staging distribution based on the updated traffic configuration. API To update a continuous deployment policy, use UpdateContinuousDeploymentPolicy. Work with a staging distribution and continuous deployment policy 136 Amazon CloudFront Developer Guide Promote a staging distribution configuration The following procedures show you how to promote a staging distribution configuration. Console When you promote a staging distribution, CloudFront copies the configuration from the staging distribution to the primary distribution. CloudFront also disables the continuous deployment policy and routes all traffic to the primary distribution. After you promote a configuration, you can reuse the same staging distribution the next time you want to test a configuration change. To promote a staging distribution's configuration (console) 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions. 3. Choose the primary distribution. This is the distribution that currently serves production traffic, the one from which you created the staging distribution. In the Continuous deployment section, choose Promote. Type confirm and then choose Promote. 4. 5. CLI When you promote a staging distribution, CloudFront copies the configuration from the staging distribution to the primary distribution. CloudFront also disables the continuous deployment policy and routes all traffic to the primary distribution. After you promote a configuration, you can reuse the same staging distribution the next time you want to test a configuration change. To promote a staging distribution's configuration (CLI) • Use the aws cloudfront update-distribution-with-staging-config command to promote the staging distribution's configuration to the primary distribution. The following example command uses escape characters (\) and line breaks for readability, but you should omit these from the command. In the following example command: • Replace primary_distribution_ID with the ID of the primary distribution. Work with a staging distribution and continuous deployment policy 137 Amazon CloudFront Developer |
AmazonCloudFront_DevGuide-056 | AmazonCloudFront_DevGuide.pdf | 56 | traffic to the primary distribution. After you promote a configuration, you can reuse the same staging distribution the next time you want to test a configuration change. To promote a staging distribution's configuration (CLI) • Use the aws cloudfront update-distribution-with-staging-config command to promote the staging distribution's configuration to the primary distribution. The following example command uses escape characters (\) and line breaks for readability, but you should omit these from the command. In the following example command: • Replace primary_distribution_ID with the ID of the primary distribution. Work with a staging distribution and continuous deployment policy 137 Amazon CloudFront Developer Guide • Replace staging_distribution_ID with the ID of the staging distribution. • Replace primary_distribution_ETag and staging_distribution_ETag with the ETag values of the primary and staging distributions. Make sure the primary distribution's value is first, as shown in the example. aws cloudfront update-distribution-with-staging-config -- id primary_distribution_ID \ --staging-distribution- id staging_distribution_ID \ --if-match 'primary_distribution_ETag,staging_distribution_ETag' API To promote a staging distribution's configuration to the primary distribution, use UpdateDistributionWithStagingConfig. Monitor a staging distribution To monitor the performance of a staging distribution, you can use the same metrics, logs, and reports that CloudFront provides for all distributions. For example: • You can view the default CloudFront distribution metrics (such as total requests and error rate) in the CloudFront console, and you can turn on additional metrics (such as cache hit rate and error rate by status code) for an additional cost. You can also create alarms based on these metrics. • You can view standard logs and real-time logs to get detailed information about the requests that are received by the staging distribution. Standard logs contain the following two fields that help you identify the primary distribution that the request was originally sent to before CloudFront routed it to the staging distribution: primary-distribution-id and primary- distribution-dns-name. • You can view and download reports in the CloudFront console, for example the cache statistics report. Monitor a staging distribution 138 Amazon CloudFront Developer Guide Learn how continuous deployment works The following topics explain how CloudFront continuous deployment works. Topics • Route requests to the staging distribution • Session stickiness for weight-based configurations • Update primary and staging distributions • Primary and staging distributions don't share a cache Route requests to the staging distribution When you use CloudFront continuous deployment, you don't need to change anything about the viewer requests. Viewers cannot send requests directly to a staging distribution using a DNS name, IP address, or CNAME. Instead, viewers send requests to the primary (production) distribution, and CloudFront routes some of those requests to the staging distribution based on the traffic configuration settings in the continuous deployment policy. There are two types of traffic configurations: Weight-based A weight-based configuration routes the specified percentage of viewer requests to the staging distribution. When you use a weight-based configuration, you can also enable session stickiness, which helps make sure that CloudFront treats requests from the same viewer as part of a single session. For more information, see the section called “Session stickiness for weight-based configurations”. Header-based A header-based configuration routes requests to the staging distribution when the viewer request contains a specific HTTP header (you specify the header and the value). Requests that don't contain the specified header and value are routed to the primary distribution. This configuration is useful for local testing, or when you have control over the viewer requests. Note Headers routed to your staging distribution must contain the prefix aws-cf-cd-. Learn how continuous deployment works 139 Amazon CloudFront Developer Guide Session stickiness for weight-based configurations When you use a weight-based configuration to route traffic to a staging distribution, you can also enable session stickiness, which helps make sure that CloudFront treats requests from the same viewer as a single session. When you enable session stickiness, CloudFront sets a cookie so that all requests from the same viewer in a single session are served by one distribution, either the primary or staging. When you enable session stickiness, you can also specify the idle duration. If the viewer is idle (sends no requests) for this amount of time, the session expires and CloudFront treats future requests from this viewer as a new session. You specify the idle duration as a number of seconds, from 300 (five minutes) to 3600 (one hour). In the following cases, CloudFront resets all sessions (even active ones) and considers all requests to be a new session: • You disable or enable the continuous deployment policy • You disable or enable the session stickiness setting Update primary and staging distributions When a primary distribution has an attached continuous deployment policy, the following configuration changes are available for both primary and staging distributions: • All cache behavior settings, including the default cache behavior • All origin settings (origins and origin groups) • Custom error responses (error |
AmazonCloudFront_DevGuide-057 | AmazonCloudFront_DevGuide.pdf | 57 | a number of seconds, from 300 (five minutes) to 3600 (one hour). In the following cases, CloudFront resets all sessions (even active ones) and considers all requests to be a new session: • You disable or enable the continuous deployment policy • You disable or enable the session stickiness setting Update primary and staging distributions When a primary distribution has an attached continuous deployment policy, the following configuration changes are available for both primary and staging distributions: • All cache behavior settings, including the default cache behavior • All origin settings (origins and origin groups) • Custom error responses (error pages) • Geographic restrictions • Default root object • Logging settings • Description (comment) You can also update external resources that are referenced in a distribution's configuration—such as a cache policy, a response headers policy, a CloudFront function, or a Lambda@Edge function. Learn how continuous deployment works 140 Amazon CloudFront Developer Guide Primary and staging distributions don't share a cache The primary and staging distributions don't share a cache. When CloudFront sends the first request to a staging distribution, its cache is empty. As requests arrive at the staging distribution, it begins caching responses (if configured to do so). Quotas and other considerations for continuous deployment CloudFront continuous deployment is subject to the following quotas and other considerations. Quotas • Maximum number of staging distributions per AWS account: 20 • Maximum number of continuous deployment policies per AWS account: 20 • Maximum percentage of traffic you can send to a staging distribution in a weight-based configuration: 15% • Minimum and maximum values for session stickiness idle duration: 300–3600 seconds For more information, see Quotas. Note When using continuous deployment and your primary distribution is set with OAC for S3 bucket access, update your S3 bucket policy to allow access for the staging distribution. For example S3 bucket policies, see the section called “Grant CloudFront permission to access the S3 bucket”. AWS WAF web ACLs If you enable continuous distribution for your distribution, the following considerations apply for AWS WAF: • You can't associate an AWS WAF web access control list (ACL) to the distribution if it's the first time that ACL has been associated with the distribution. • You can't disassociate an AWS WAF web ACL from the distribution. Quotas and other considerations for continuous deployment 141 Amazon CloudFront Developer Guide Before you can do the preceding tasks, you must delete the continuous deployment policy for your production distribution. This also deletes the staging distribution. For more information, see Use AWS WAF protections. Cases when CloudFront sends all requests to the primary distribution In certain cases, such as periods of high resource utilization, CloudFront might send all requests to the primary distribution regardless of what's specified in the continuous deployment policy. CloudFront sends all requests to the primary distribution during peak traffic hours, regardless of what's specified in the continuous deployment policy. Peak traffic refers to the traffic on the CloudFront service, and not the traffic on your distribution. HTTP/3 You cannot use continuous deployment with a distribution that supports HTTP/3. Use custom URLs by adding alternate domain names (CNAMEs) When you create a distribution, CloudFront provides a domain name for it, such as d111111abcdef8.cloudfront.net. Instead of using this provided domain name, you can use an alternate domain name (also known as a CNAME). To learn how to use your own domain name, such as www.example.com, see the following topics: Topics • Requirements for using alternate domain names • Restrictions on using alternate domain names • Add an alternate domain name • Move an alternate domain name to a different distribution • Remove an alternate domain name • Use wildcards in alternate domain names Requirements for using alternate domain names When you add an alternate domain name, such as www.example.com, to a CloudFront distribution, the following are requirements: Use custom URLs 142 Amazon CloudFront Developer Guide Alternate domain names must be lowercase All alternate domain names (CNAMEs) must be lowercase. Alternate domain names must be covered by a valid SSL/TLS certificate To add an alternate domain name (CNAME) to a CloudFront distribution, you must attach to your distribution a trusted, valid SSL/TLS certificate that covers the alternate domain name. This ensures that only people with access to your domain’s certificate can associate with CloudFront a CNAME related to your domain. A trusted certificate is one that is issued by AWS Certificate Manager (ACM) or by another valid certificate authority (CA). You can use a self-signed certificate to validate an existing CNAME, but not for a new CNAME. CloudFront supports the same certificate authorities as Mozilla. For the current list, see Mozilla Included CA Certificate List. For information about intermediate certificates when using a third-party CA, see Intermediate certificates. To verify an alternate domain name by using the certificate that you |
AmazonCloudFront_DevGuide-058 | AmazonCloudFront_DevGuide.pdf | 58 | ensures that only people with access to your domain’s certificate can associate with CloudFront a CNAME related to your domain. A trusted certificate is one that is issued by AWS Certificate Manager (ACM) or by another valid certificate authority (CA). You can use a self-signed certificate to validate an existing CNAME, but not for a new CNAME. CloudFront supports the same certificate authorities as Mozilla. For the current list, see Mozilla Included CA Certificate List. For information about intermediate certificates when using a third-party CA, see Intermediate certificates. To verify an alternate domain name by using the certificate that you attach, including alternate domain names that include wildcards, CloudFront checks the subject alternative name (SAN) on the certificate. The alternate domain name that you’re adding must be covered by the SAN. Note Only one certificate can be attached to a CloudFront distribution at a time. You prove that you are authorized to add a specific alternate domain name to your distribution by doing one of the following: • Attaching a certificate that includes the alternate domain name, like product- name.example.com. • Attaching a certificate that includes a * wildcard at the beginning of a domain name, to cover multiple subdomains with one certificate. When you specify a wildcard, you can add multiple subdomains as alternate domain names in CloudFront. The following examples illustrate how using wildcards in domain names in a certificate work to authorize you to add specific alternate domain names in CloudFront. • You want to add marketing.example.com as an alternate domain name. You list in your certificate the following domain name: *.example.com. When you attach this certificate to CloudFront, you can add any alternate domain name for your distribution that replaces the Requirements for using alternate domain names 143 Amazon CloudFront Developer Guide wildcard at that level, including marketing.example.com. You can also, for example, add the following alternate domain names: • product.example.com • api.example.com However, you can’t add alternate domain names that are at levels higher or lower than the wildcard. For example, you can’t add the alternate domain names example.com or marketing.product.example.com. • You want to add example.com as an alternate domain name. To do this, you must list the domain name example.com itself on the certificate that you attach to your distribution. • You want to add marketing.product.example.com as an alternate domain name. To do this, you can list *.product.example.com on the certificate, or you can list marketing.product.example.com itself on the certificate. Permission to change DNS configuration When you add alternate domain names, you must create CNAME records to route DNS queries for the alternate domain names to your CloudFront distribution. To do this, you must have permission to create CNAME records with the DNS service provider for the alternate domain names that you’re using. Typically, this means that you own the domains, but you might be developing an application for the domain owner. Alternate domain names and HTTPS If you want viewers to use HTTPS with an alternate domain name, you must complete some additional configuration. For more information, see Use alternate domain names and HTTPS. Restrictions on using alternate domain names Note the following restrictions on using alternate domain names: Maximum number of alternate domain names For the current maximum number of alternate domain names that you can add to a distribution, or to request a higher quota (formerly known as limit), see General quotas on distributions. Restrictions on using alternate domain names 144 Amazon CloudFront Developer Guide Duplicate and overlapping alternate domain names You cannot add an alternate domain name to a CloudFront distribution if the same alternate domain name already exists in another CloudFront distribution, even if your AWS account owns the other distribution. However, you can add a wildcard alternate domain name, such as *.example.com, that includes (that overlaps with) a non-wildcard alternate domain name, such as www.example.com. If you have overlapping alternate domain names in two distributions, CloudFront sends the request to the distribution with the more specific name match, regardless of the distribution that the DNS record points to. For example, marketing.domain.com is more specific than *.domain.com. If you have an existing wildcard DNS entry that points to a CloudFront distribution and you receive an incorrectly configured DNS error when trying to add a new CNAME with a more specific name, see CloudFront returns an incorrectly configured DNS record error when I try to add a new CNAME. Domain fronting CloudFront includes protection against domain fronting occurring across different AWS accounts. Domain fronting is a scenario in which a non-standard client creates a TLS/SSL connection to a domain name in one AWS account, but then makes an HTTPS request for an unrelated name in another AWS account. For example, the TLS connection might connect to www.example.com, and then send an HTTP request for www.example.org. To prevent cases where |
AmazonCloudFront_DevGuide-059 | AmazonCloudFront_DevGuide.pdf | 59 | error when trying to add a new CNAME with a more specific name, see CloudFront returns an incorrectly configured DNS record error when I try to add a new CNAME. Domain fronting CloudFront includes protection against domain fronting occurring across different AWS accounts. Domain fronting is a scenario in which a non-standard client creates a TLS/SSL connection to a domain name in one AWS account, but then makes an HTTPS request for an unrelated name in another AWS account. For example, the TLS connection might connect to www.example.com, and then send an HTTP request for www.example.org. To prevent cases where domain fronting crosses different AWS accounts, CloudFront makes sure that the AWS account that owns the certificate that it serves for a specific connection always matches the AWS account that owns the request that it handles on that same connection. If the two AWS account numbers do not match, CloudFront responds with an HTTP 421 Misdirected Request response to give the client a chance to connect using the correct domain. Adding an alternate domain name at the top node (zone apex) for a domain When you add an alternate domain name to a distribution, you typically create a CNAME record in your DNS configuration to route DNS queries for the domain name to your CloudFront distribution. However, you can’t create a CNAME record for the top node of a DNS namespace, also known as the zone apex; the DNS protocol doesn’t allow it. For example, if you register the DNS name example.com, the zone apex is example.com. You can’t create a CNAME record for example.com, but you can create CNAME records for www.example.com, newproduct.example.com, and so on. Restrictions on using alternate domain names 145 Amazon CloudFront Developer Guide If you’re using Route 53 as your DNS service, you can create an alias resource record set, which has two advantages over CNAME records. You can create an alias resource record set for a domain name at the top node (example.com). In addition, when you use an alias resource record set, you don’t pay for Route 53 queries. Note If you enable IPv6, you must create two alias resource record sets: one to route IPv4 traffic (an A record) and one to route IPv6 traffic (an AAAA record). For more information, see Enable IPv6 in the topic Distribution settings reference. For more information, see Routing traffic to an Amazon CloudFront web distribution by using your domain name in the Amazon Route 53 Developer Guide. If you're not using Route 53 for your DNS, you can request Anycast static IP addresses to route apex domains like example.com to CloudFront. For more information, see Request Anycast static IPs to use for allowlisting. Add an alternate domain name The following task list describes how to use the CloudFront console to add an alternate domain name to your distribution so that you can use your own domain name in your links instead of the CloudFront domain name. For information about updating your distribution using the CloudFront API, see Configure distributions. Note If you want viewers to use HTTPS with your alternate domain name, see Use alternate domain names and HTTPS. Before you begin: Make sure that you do the following before you update your distribution to add an alternate domain name: • Register the domain name with Route 53 or another domain registrar. Add an alternate domain name 146 Amazon CloudFront Developer Guide • Get an SSL/TLS certificate from an authorized certificate authority (CA) that covers the domain name. Add the certificate to your distribution to validate that you are authorized to use the domain. For more information, see Requirements for using alternate domain names. Add an alternate domain name 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose the ID for the distribution that you want to update. 3. On the General tab, choose Edit. 4. Update the following values: Alternate Domain Names (CNAMEs) Add your alternate domain names. Separate domain names with commas, or type each domain name on a new line. SSL Certificate Choose the following setting: • Use HTTPS – Choose Custom SSL Certificate, and then choose a certificate from the list. The list includes certificates provisioned by AWS Certificate Manager (ACM), certificates that you purchased from another CA and uploaded to ACM, and certificates that you purchased from another CA and uploaded to the IAM certificate store. If you uploaded a certificate to the IAM certificate store but it doesn’t appear in the list, review the procedure Import an SSL/TLS certificate to confirm that you correctly uploaded the certificate. If you choose this setting, we recommend that you use only an alternate domain name in your object URLs (https://www.example.com/logo.jpg). If you use your CloudFront distribution domain name (https://d111111abcdef8.cloudfront.net.cloudfront.net/ logo.jpg), a viewer might |
AmazonCloudFront_DevGuide-060 | AmazonCloudFront_DevGuide.pdf | 60 | list includes certificates provisioned by AWS Certificate Manager (ACM), certificates that you purchased from another CA and uploaded to ACM, and certificates that you purchased from another CA and uploaded to the IAM certificate store. If you uploaded a certificate to the IAM certificate store but it doesn’t appear in the list, review the procedure Import an SSL/TLS certificate to confirm that you correctly uploaded the certificate. If you choose this setting, we recommend that you use only an alternate domain name in your object URLs (https://www.example.com/logo.jpg). If you use your CloudFront distribution domain name (https://d111111abcdef8.cloudfront.net.cloudfront.net/ logo.jpg), a viewer might behave as follows, depending on the value that you choose for Clients Supported: • All Clients: If the viewer doesn’t support SNI, it displays a warning because the CloudFront domain name doesn’t match the domain name in your TLS/SSL certificate. • Only Clients that Support Server Name Indication (SNI): CloudFront drops the connection with the viewer without returning the object. Add an alternate domain name 147 Amazon CloudFront Clients Supported Choose an option: Developer Guide • All Clients: CloudFront serves your HTTPS content using dedicated IP addresses. If you select this option, you incur additional charges when you associate your SSL/ TLS certificate with a distribution that is enabled. For more information, see Amazon CloudFront Pricing. • Only Clients that Support Server Name Indication (SNI) (Recommended): Older browsers or other clients that don't support SNI must use another method to access your content. For more information, see Choose how CloudFront serves HTTPS requests. 5. Choose Yes, Edit. 6. On the General tab for the distribution, confirm that Distribution Status has changed to Deployed. If you try to use an alternate domain name before the updates to your distribution have been deployed, the links that you create in the following steps might not work. 7. Configure the DNS service for the alternate domain name (such as www.example.com) to route traffic to the CloudFront domain name for your distribution (such as d111111abcdef8.cloudfront.net). The method that you use depends on whether you’re using Route 53 as the DNS service provider for the domain or another provider. Note If your DNS record already points to a distribution that is not the distribution that you are updating, then you only add the alternate domain name to your distribution after you update your DNS. For more information, see Restrictions on using alternate domain names. Route 53 Create an alias resource record set. With an alias resource record set, you don’t pay for Route 53 queries. In addition, you can create an alias resource record set for the root domain name (example.com), which DNS doesn’t allow for CNAMEs. For more information, see Routing traffic to an Amazon CloudFront web distribution by using your domain name in the Amazon Route 53 Developer Guide. Add an alternate domain name 148 Amazon CloudFront Developer Guide Another DNS service provider Use the method provided by your DNS service provider to add a CNAME record for your domain. This new CNAME record will redirect DNS queries from your alternate domain name (for example, www.example.com) to the CloudFront domain name for your distribution (for example, d111111abcdef8.cloudfront.net). For more information, see the documentation provided by your DNS service provider. Important If you already have an existing CNAME record for your alternate domain name, update that record or replace it with a new one that points to the CloudFront domain name for your distribution. 8. Using dig or a similar DNS tool, confirm that the DNS configuration that you created in the previous step points to the domain name for your distribution. The following example shows a dig request on the www.example.com domain, as well as the relevant part of the response. PROMPT> dig www.example.com ; <<> DiG 9.3.3rc2 <<> www.example.com ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 15917 ;; flags: qr rd ra; QUERY: 1, ANSWER: 9, AUTHORITY: 2, ADDITIONAL: 0 ;; QUESTION SECTION: ;www.example.com. IN A ;; ANSWER SECTION: www.example.com. 10800 IN CNAME d111111abcdef8.cloudfront.net. ... The answer section shows a CNAME record that routes queries for www.example.com to the CloudFront distribution domain name d111111abcdef8.cloudfront.net. If the name on the right side of CNAME is the domain name for your CloudFront distribution, the CNAME record is configured correctly. If it’s any other value, for example, the domain name for your Amazon Add an alternate domain name 149 Amazon CloudFront Developer Guide S3 bucket, then the CNAME record is configured incorrectly. In that case, go back to step 7 and correct the CNAME record to point to the domain name for your distribution. 9. Test the alternate domain name by visiting URLs with your domain name instead of the CloudFront domain name for your distribution. 10. In your application, change the URLs for your objects to use your |
AmazonCloudFront_DevGuide-061 | AmazonCloudFront_DevGuide.pdf | 61 | name for your CloudFront distribution, the CNAME record is configured correctly. If it’s any other value, for example, the domain name for your Amazon Add an alternate domain name 149 Amazon CloudFront Developer Guide S3 bucket, then the CNAME record is configured incorrectly. In that case, go back to step 7 and correct the CNAME record to point to the domain name for your distribution. 9. Test the alternate domain name by visiting URLs with your domain name instead of the CloudFront domain name for your distribution. 10. In your application, change the URLs for your objects to use your alternate domain name instead of the domain name of your CloudFront distribution. Move an alternate domain name to a different distribution When you try to add an alternate domain name to a distribution but the alternate domain name is already in use on a different distribution, you get a CNAMEAlreadyExists error (One or more of the CNAMEs you provided are already associated with a different resource). For example, you get this error when you attempt to add www.example.com to a distribution, but www.example.com is already associated with a different distribution. In that case, you might want to move the existing alternate domain name from one distribution (the source distribution) to another (the target distribution). The following steps are an overview of the process. For more information, follow the link at each step in the overview. To move an alternate domain name 1. Set up the target distribution. This distribution must have an SSL/TLS certificate that covers the alternate domain name that you are moving. For more information, see Set up the target distribution. 2. Find the source distribution. You can use the AWS Command Line Interface (AWS CLI) to find the distribution that the alternate domain name is associated with. For more information, see Find the source distribution. 3. Move the alternate domain name. The way you do this depends on whether the source and target distributions are in the same AWS account. For more information, see the section called “Move the alternate domain name”. Set up the target distribution Before you can move an alternate domain name, you must set up the target distribution (the distribution that you are moving the alternate domain name to). Move an alternate domain name to a different distribution 150 Amazon CloudFront Developer Guide To set up the target distribution 1. Get an SSL/TLS certificate that includes the alternate domain name that you are moving. If you don’t have one, you can request one from AWS Certificate Manager (ACM), or get one from another certificate authority (CA) and import it into ACM. Make sure that you request or import the certificate in the US East (N. Virginia) (us-east-1) Region. 2. If you haven’t created the target distribution, create one now. As part of creating the target distribution, associate your certificate (from the previous step) with the distribution. For more information, see Create a distribution. If you already have a target distribution, associate your certificate (from the previous step) with the target distribution. For more information, see Update a distribution. 3. Create a DNS TXT record that associates the alternate domain name with the distribution domain name of the target distribution. Create your TXT record with an underscore (_) in front of the alternate domain name. The following shows an example TXT record in DNS: _www.example.com TXT d111111abcdef8.cloudfront.net CloudFront uses this TXT record to validate your ownership of the alternate domain name. Find the source distribution Before you move an alternate domain name from one distribution to another, you should find the source distribution (the distribution where the alternate domain name is currently in use). When you know the AWS account ID of both the source and target distributions, you can determine how to move the alternate domain name. To find the source distribution for the alternate domain name 1. Use the CloudFront list-conflicting-aliases command in the AWS Command Line Interface (AWS CLI) as shown in the following example. Replace www.example.com with the alternate domain name, and EDFDVBD6EXAMPLE with the ID of the target distribution that you set up previously. Run this command using credentials that are in the same AWS account as the target distribution. To use this command, you must have cloudfront:GetDistribution and cloudfront:ListConflictingAlias permissions on the target distribution. Move an alternate domain name to a different distribution 151 Amazon CloudFront Developer Guide aws cloudfront list-conflicting-aliases --alias www.example.com --distribution- id EDFDVBD6EXAMPLE The command’s output shows a list of all the alternate domain names that conflict or overlap with the provided one. For example: • If you provide www.example.com to the command, the command’s output includes www.example.com and the overlapping wildcard alternate domain name (*.example.com) if it exists. • If you provide *.example.com to the command, the command’s output includes *.example.com and any alternate |
AmazonCloudFront_DevGuide-062 | AmazonCloudFront_DevGuide.pdf | 62 | distribution. To use this command, you must have cloudfront:GetDistribution and cloudfront:ListConflictingAlias permissions on the target distribution. Move an alternate domain name to a different distribution 151 Amazon CloudFront Developer Guide aws cloudfront list-conflicting-aliases --alias www.example.com --distribution- id EDFDVBD6EXAMPLE The command’s output shows a list of all the alternate domain names that conflict or overlap with the provided one. For example: • If you provide www.example.com to the command, the command’s output includes www.example.com and the overlapping wildcard alternate domain name (*.example.com) if it exists. • If you provide *.example.com to the command, the command’s output includes *.example.com and any alternate domain names covered by that wildcard (for example, www.example.com, test.example.com, dev.example.com, and so on). For each alternate domain name in the command’s output, you can see the ID of the distribution that it’s associated with, and the AWS account ID that owns the distribution. The distribution and account IDs are partially hidden, which allows you to identify the distributions and accounts that you own, but helps to protect the information of ones that you don’t own. 2. In the command’s output, find the distribution for the alternate domain name that you are moving, and note the source distribution’s AWS account ID. Compare the source distribution’s account ID with the account ID where you created the target distribution, and determine whether these two distribution are in the same AWS account. This helps you determine how to move the alternate domain name. To move the alternate domain name, see the following topic. Move the alternate domain name Depending on your situation, choose from the following ways to move the alternate domain name: If the source and target distributions are in the same AWS account Use the associate-alias command in the AWS CLI to move the alternate domain name. This method works for all same-account moves, including when the alternate domain name is an apex domain (also called a root domain, like example.com). For more information, see the section called “Use associate-alias to move an alternate domain name”. Move an alternate domain name to a different distribution 152 Amazon CloudFront Developer Guide If the source and target distributions are in different AWS accounts If you have access to the source distribution, the alternate domain name is not an apex domain (also called a root domain, like example.com), and you are not already using a wildcard that overlaps with that alternate domain name, use a wildcard to move the alternate domain name. For more information, see the section called “Use a wildcard to move an alternate domain name”. If you don’t have access to the source distribution’s AWS account, you can try using the associate-alias command in the AWS CLI to move the alternate domain name. If the source distribution is disabled, you can move the alternate domain name. For more information, see the section called “Use associate-alias to move an alternate domain name”. If the associate-alias command doesn’t work, contact Support. For more information, see the section called “Contact Support to move an alternate domain name”. Use associate-alias to move an alternate domain name If the source distribution is in the same AWS account as the target distribution, or if it’s in a different account but disabled, you can use the CloudFront associate-alias command in the AWS CLI to move the alternate domain name. To use associate-alias to move an alternate domain name 1. Use the AWS CLI to run the CloudFront associate-alias command, as shown in the following example. Replace www.example.com with the alternate domain name, and EDFDVBD6EXAMPLE with the target distribution ID. Run this command using credentials that are in the same AWS account as the target distribution. Note the following restrictions for using this command: • You must have cloudfront:AssociateAlias and cloudfront:UpdateDistribution permissions on the target distribution. • If the source and target distributions are in the same AWS account, you must have cloudfront:UpdateDistribution permission on the source distribution. • If the source and target distributions are in different AWS accounts, the source distribution must be disabled. • The target distribution must be set up as described in the section called “Set up the target distribution”. Move an alternate domain name to a different distribution 153 Amazon CloudFront Developer Guide aws cloudfront associate-alias --alias www.example.com --target-distribution- id EDFDVBD6EXAMPLE This command updates both distributions by removing the alternate domain name from the source distribution and adding it to the target distribution. 2. After the target distribution is fully deployed, update your DNS configuration to point the alternate domain name’s DNS record to the distribution domain name of the target distribution. Use a wildcard to move an alternate domain name If the source distribution is in a different AWS account than the target distribution, and the source distribution is enabled, you can use a wildcard to move the alternate domain name. Note |
AmazonCloudFront_DevGuide-063 | AmazonCloudFront_DevGuide.pdf | 63 | aws cloudfront associate-alias --alias www.example.com --target-distribution- id EDFDVBD6EXAMPLE This command updates both distributions by removing the alternate domain name from the source distribution and adding it to the target distribution. 2. After the target distribution is fully deployed, update your DNS configuration to point the alternate domain name’s DNS record to the distribution domain name of the target distribution. Use a wildcard to move an alternate domain name If the source distribution is in a different AWS account than the target distribution, and the source distribution is enabled, you can use a wildcard to move the alternate domain name. Note You can’t use a wildcard to move an apex domain (like example.com). To move an apex domain when the source and target distributions are in different AWS accounts, contact Support. For more information, see the section called “Contact Support to move an alternate domain name”. To use a wildcard to move an alternate domain name Note This process involves multiple updates to your distributions. Wait for each distribution to fully deploy the latest change before proceeding to the next step. 1. Update the target distribution to add a wildcard alternate domain name that covers the alternate domain name that you are moving. For example, if the alternate domain name that you’re moving is www.example.com, add the alternate domain name *.example.com to the target distribution. To do this, the SSL/TLS certificate on the target distribution must Move an alternate domain name to a different distribution 154 Amazon CloudFront Developer Guide include the wildcard domain name. For more information, see the section called “Update a distribution”. 2. Update the DNS settings for the alternate domain name to point to the domain name of the target distribution. For example, if the alternate domain name that you’re moving is www.example.com, update the DNS record for www.example.com to route traffic to the domain name of the target distribution (for example d111111abcdef8.cloudfront.net). Note Even after you update the DNS settings, the alternate domain name is still served by the source distribution because that’s where the alternate domain name is currently configured. 3. Update the source distribution to remove the alternate domain name. For more information, see Update a distribution. 4. Update the target distribution to add the alternate domain name. For more information, see Update a distribution. 5. Use dig (or a similar DNS query tool) to validate that the DNS record for the alternate domain name resolves to the domain name of the target distribution. 6. (Optional) Update the target distribution to remove the wildcard alternate domain name. Contact Support to move an alternate domain name If the source and target distributions are in different AWS accounts, and you don’t have access to the source distribution’s AWS account or can’t disable the source distribution, you can contact Support to move the alternate domain name. To contact Support to move an alternate domain name 1. Set up a target distribution, including the DNS TXT record that points to the target distribution. For more information, see Set up the target distribution. 2. Contact Support to request that they verify that you own the domain, and move the domain to the new CloudFront distribution for you. 3. After the target distribution is fully deployed, update your DNS configuration to point the alternate domain name’s DNS record to the distribution domain name of the target distribution. Move an alternate domain name to a different distribution 155 Amazon CloudFront Developer Guide Remove an alternate domain name If you want to stop routing traffic for a domain or subdomain to a CloudFront distribution, follow the steps in this section to update both the DNS configuration and the CloudFront distribution. It’s important that you remove the alternate domain names from the distribution as well as update your DNS configuration. This helps prevent issues later if you want to associate the domain name with another CloudFront distribution. If an alternate domain name is already associated with one distribution, it can’t be set up with another. Note If you want to remove the alternate domain name from this distribution so you can add it to another one, follow the steps in Move an alternate domain name to a different distribution. If you follow the steps here instead (to remove a domain) and then add the domain to another distribution, there will be a period of time during which the domain won’t link to the new distribution because CloudFront is propagating to the updates to edge locations. To remove an alternate domain name from a distribution 1. To start, route internet traffic for your domain to another resource that isn’t your CloudFront distribution, such as an Elastic Load Balancing load balancer. Or you can delete the DNS record that’s routing traffic to CloudFront. Do one of the following, depending on the DNS service for your |
AmazonCloudFront_DevGuide-064 | AmazonCloudFront_DevGuide.pdf | 64 | steps here instead (to remove a domain) and then add the domain to another distribution, there will be a period of time during which the domain won’t link to the new distribution because CloudFront is propagating to the updates to edge locations. To remove an alternate domain name from a distribution 1. To start, route internet traffic for your domain to another resource that isn’t your CloudFront distribution, such as an Elastic Load Balancing load balancer. Or you can delete the DNS record that’s routing traffic to CloudFront. Do one of the following, depending on the DNS service for your domain: • If you’re using Route 53, update or delete alias records or CNAME records. For more information, see Editing records or Deleting records. • If you’re using another DNS service provider, use the method provided by the DNS service provider to update or delete the CNAME record that directs traffic to CloudFront. For more information, see the documentation provided by your DNS service provider. 2. After you update your domain’s DNS records, wait until the changes have propagated and DNS resolvers are routing traffic to the new resource. You can check to see when this is complete by creating some test links that use your domain in the URL. Remove an alternate domain name 156 Amazon CloudFront Developer Guide 3. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home, and update your CloudFront distribution to remove the domain name by doing the following: a. Choose the ID for the distribution that you want to update. b. On the General tab, choose Edit. c. In Alternate Domain Names (CNAMEs), remove the alternate domain name (or domain names) that you no longer want to use for your distribution. d. Choose Yes, Edit. Use wildcards in alternate domain names When you add alternate domain names, you can use the * wildcard at the beginning of a domain name instead of adding subdomains individually. For example, with an alternate domain name of *.example.com, you can use any domain name that ends with example.com in your URLs, such as www.example.com, product-name.example.com, marketing.product-name.example.com, and so on. The path to the object is the same regardless of the domain name, for example: • www.example.com/images/image.jpg • product-name.example.com/images/image.jpg • marketing.product-name.example.com/images/image.jpg Follow these requirements for alternate domain names that include wildcards: • The alternate domain name must begin with an asterisk and a dot (*.). • You cannot use a wildcard to replace part of a subdomain name, like this: *domain.example.com. • You cannot replace a subdomain in the middle of a domain name, like this: subdomain.*.example.com. • All alternate domain names, including alternate domain names that use wildcards, must be covered by the subject alternative name (SAN) on the certificate. A wildcard alternate domain name, such as *.example.com, can include another alternate domain name that’s in use, such as example.com. Use wildcards in alternate domain names 157 Amazon CloudFront Developer Guide Use WebSockets with CloudFront distributions Amazon CloudFront supports using WebSocket, a TCP-based protocol that is useful when you need long-lived bidirectional connections between clients and servers. A persistent connection is often a requirement with real-time applications. The scenarios in which you might use WebSockets include social chat platforms, online collaboration workspaces, multi-player gaming, and services that provide real-time data feeds like financial trading platforms. Data over a WebSocket connection can flow in both directions for full-duplex communication. WebSocket functionality is automatically enabled to work with any distribution. To use WebSockets, configure one of the following in the cache behavior that's attached to your distribution: • Forward all viewer request headers to your origin. You can use the AllViewer managed origin request policy. • Specifically forward the Sec-WebSocket-Key and Sec-WebSocket-Version request headers in your origin request policy. How the WebSocket protocol works The WebSocket protocol is an independent, TCP-based protocol that allows you to avoid some of the overhead—and potentially increased latency—of HTTP. To establish a WebSocket connection, the client sends a regular HTTP request that uses HTTP's upgrade semantics to change the protocol. The server can then complete the handshake. The WebSocket connection remains open and either the client or server can send data frames to each other without having to establish new connections each time. By default, the WebSocket protocol uses port 80 for regular WebSocket connections and port 443 for WebSocket connections over TLS/SSL. The options that you choose for your CloudFront Viewer protocol policy and Protocol (custom origins only) apply to WebSocket connections as well as to HTTP traffic. WebSocket requirements WebSocket requests must comply with RFC 6455 in the following standard formats. Use WebSockets 158 Developer Guide Amazon CloudFront Example Sample client request GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: https://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Example Sample server response HTTP/1.1 101 |
AmazonCloudFront_DevGuide-065 | AmazonCloudFront_DevGuide.pdf | 65 | establish new connections each time. By default, the WebSocket protocol uses port 80 for regular WebSocket connections and port 443 for WebSocket connections over TLS/SSL. The options that you choose for your CloudFront Viewer protocol policy and Protocol (custom origins only) apply to WebSocket connections as well as to HTTP traffic. WebSocket requirements WebSocket requests must comply with RFC 6455 in the following standard formats. Use WebSockets 158 Developer Guide Amazon CloudFront Example Sample client request GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: https://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Example Sample server response HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat If the WebSocket connection is disconnected by the client or server, or by a network disruption, client applications are expected to re-initiate the connection with the server. Recommended WebSocket headers To avoid unexpected compression-related issues when using WebSockets, we recommend that you include the following headers in an origin request policy: • Sec-WebSocket-Key • Sec-WebSocket-Version • Sec-WebSocket-Protocol • Sec-WebSocket-Accept • Sec-WebSocket-Extensions Request Anycast static IPs to use for allowlisting You can request Anycast static IPs from CloudFront to use with your distributions. Anycast static IP lists contain IPv4 IP addresses that are dedicated to your AWS account and spread across geographic regions. Recommended WebSocket headers 159 Amazon CloudFront Developer Guide You can request 21 Anycast static IP addresses to allowlist with network providers so that you can waive data charges for viewers who access your application. Alternatively, you can use these static IPs within outbound security firewalls to control traffic exchange with approved applications. If you want to enable routing of apex domains (such as example.com) directly to your CloudFront distributions, you can request 3 Anycast static IP addresses for this use case. Then, add A records in your DNS to point the apex domain to CloudFront. Anycast static IPs work with Server Name Indication (SNI). For more information, see Use SNI to serve HTTPS requests (works for most clients). Prerequisites To use Anycast static IP lists with your CloudFront distribution, you must: • Turn off IPv6 for the distribution that you want to use with your Anycast static IP list. • Select Use all edge locations for the price class for the distribution. For more information about pricing, see CloudFront pricing. Request an Anycast static IP list Request an Anycast static IP list to use with your CloudFront distribution. To request an Anycast static IP list 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. In the left navigation pane, choose Static IPs. For Request, choose the link to contact CloudFront support engineering. 2. 3. 4. Provide your workload information (request bytes per second and requests per second). 5. CloudFront support engineering reviews your request. The review process might take up to two days. After your request is approved, you can create an Anycast static IP list and associate it with one or more distributions. Prerequisites 160 Amazon CloudFront Developer Guide Create an Anycast static IP list Before you begin, request an Anycast static IP list as explained in the preceding section. To create an Anycast static IP list 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the left navigation pane, choose Static IPs. 3. Choose Create Anycast IP list. 4. 5. For Name, enter a name. For Static IP use cases, select the appropriate use case. 6. Review the service terms and pricing, and choose Submit. After your static IP list is created, you can view the allocated IP addresses on your static IP list detail page. You can also associate distributions with the static IP list. Associate an Anycast static IP list with an existing distribution Before you begin, request and create an Anycast static IP list as explained in the preceding sections. Also confirm that you have turned off IPv6 for your distribution and selected Use all edge locations (best performance) for the price class. To associate an Anycast static IP list with an existing distribution • Do one of the following: • Associate the static IP list from the static IP list detail page: 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose Static IPs in the left navigation pane. 3. Choose the name of your static IP list. 4. Choose Associate distributions. 5. Select one or more distributions and choose Associate distributions. • Associate the static IP list from the distribution detail page: Create an Anycast static IP list 161 Amazon CloudFront Developer Guide 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose Distributions in the left navigation pane. 3. Choose the name of your distribution. 4. On the |
AmazonCloudFront_DevGuide-066 | AmazonCloudFront_DevGuide.pdf | 66 | the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose Static IPs in the left navigation pane. 3. Choose the name of your static IP list. 4. Choose Associate distributions. 5. Select one or more distributions and choose Associate distributions. • Associate the static IP list from the distribution detail page: Create an Anycast static IP list 161 Amazon CloudFront Developer Guide 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose Distributions in the left navigation pane. 3. Choose the name of your distribution. 4. On the General tab, under Settings, choose Edit. 5. For Anycast IP list, select the Anycast static IP list to use with this distribution. 6. Choose Save changes. Associate an Anycast static IP list with a new distribution Before you begin, request and create an Anycast static IP list as explained in the preceding sections. To associate an Anycast static IP list with a new distribution • Create a new distribution. For more information, see Create a CloudFront distribution in the console. For Settings, you must make the following selections to use your Anycast static IP list: • For Anycast IP list, select your Anycast static IP list from the dropdown list. • For Price class, select Use all edge locations (best performance). • For IPv6, select Off. Finish creating your distribution. You can choose any other settings and configurations that are not required for Anycast static IP lists based on your needs. For more information about quotas related to Anycast static IP lists, see Amazon CloudFront endpoints and quotas in the AWS General Reference. Using gRPC with CloudFront distributions Amazon CloudFront supports gRPC, an open-source remote procedure call (RPC) framework built on HTTP/2. gRPC offers bi-directional streaming and binary protocol that buffers payloads, making it suitable for applications that require low latency communications. CloudFront receives your gRPC requests and proxies them directly to your origins. You can use CloudFront to proxy four types of gRPC services: • Unary RPC Associate an Anycast static IP list with a new distribution 162 Amazon CloudFront • Server streaming RPC • Client streaming RPC • Bi-directional streaming RPC How gRPC works in CloudFront Developer Guide To configure gRPC in CloudFront, set an origin that provides a gRPC service as your distribution’s origin. You can use origins that provide both non-gRPC and gRPC services. CloudFront determines if the incoming request is a gRPC request or an HTTP/HTTPS request based on the Content-Type header. If a request’s Content-Type header has value of application/grpc, the request is considered a gRPC request and CloudFront will proxy the request to your origin. Note To enable a distribution to handle gRPC requests, include HTTP/2 as one of the supported HTTP versions, and allow HTTP methods, including POST. Your gRPC origin endpoint must be configured to support HTTPS, as CloudFront only supports secure (HTTPS-based) gRPC connections. gRPC only supports end-to-end HTTPS. If you're using a custom origin, verify that your Protocol settings support HTTPS. To enable gRPC support for your distribution, complete the following steps: 1. Update your distribution's cache behavior to allow HTTP methods, including the POST method. 2. After you select the POST method, select the gRPC checkbox that appears. 3. Specify HTTP/2 as one of the supported HTTP versions. For more information, see the following topics: • Allow gRPC requests over HTTP/2 • GrpcConfig in the Amazon CloudFront API Reference Because gRPC is used only for non-cacheable API traffic, your cache configurations won't affect gRPC requests. You can use an origin request policy to add custom headers to the gRPC requests that are sent to your gRPC origin. You can use AWS WAF with CloudFront to manage access to your How gRPC works in CloudFront 163 Amazon CloudFront Developer Guide gRPC distribution, control bots, and protect your gRPC applications from web exploits. CloudFront gRPC supports CloudFront Functions. In addition to HTTPS status, you will receive grpc-status along with your gRPC response. For a list of possible values for grpc-status, see Status codes and their use in gRPC. Notes gRPC doesn't support the following CloudFront features: • Continuous deployment • Custom error responses • Origin failover isn't supported with gRPC, as gRPC uses POST method. CloudFront fails over to the secondary origin only when the HTTP method of the viewer request is GET, HEAD, or OPTIONS. • CloudFront proxies gRPC requests directly to the origin and bypasses the Regional Edge Cache (REC). Because gRPC bypasses the REC, gRPC doesn't support Lambda@Edge or Origin Shield. • gRPC doesn't support AWS WAF request body inspection rules. If you enabled these rules on the web ACL for a distribution, any request that uses gRPC will ignore the request body inspection rules. All other AWS WAF rules will still apply. For more information, see |
AmazonCloudFront_DevGuide-067 | AmazonCloudFront_DevGuide.pdf | 67 | as gRPC uses POST method. CloudFront fails over to the secondary origin only when the HTTP method of the viewer request is GET, HEAD, or OPTIONS. • CloudFront proxies gRPC requests directly to the origin and bypasses the Regional Edge Cache (REC). Because gRPC bypasses the REC, gRPC doesn't support Lambda@Edge or Origin Shield. • gRPC doesn't support AWS WAF request body inspection rules. If you enabled these rules on the web ACL for a distribution, any request that uses gRPC will ignore the request body inspection rules. All other AWS WAF rules will still apply. For more information, see Enable AWS WAF for distributions. How gRPC works in CloudFront 164 Amazon CloudFront Developer Guide Caching and availability You can use CloudFront to reduce the number of requests that your origin server must respond to directly. With CloudFront caching, more objects are served from CloudFront edge locations, which are closer to your users. This reduces the load on your origin server and reduces latency. The more requests that CloudFront can serve from edge caches, the fewer viewer requests that CloudFront must forward to your origin to get the latest version or a unique version of an object. To optimize CloudFront to make as few requests to your origin as possible, consider using a CloudFront Origin Shield. For more information, see Using Amazon CloudFront Origin Shield. The proportion of requests that are served directly from the CloudFront cache compared to all requests is called the cache hit ratio. You can view the percentage of viewer requests that are hits, misses, and errors in the CloudFront console. For more information, see View CloudFront cache statistics reports. A number of factors affect the cache hit ratio. You can adjust your CloudFront distribution configuration to improve the cache hit ratio by following the guidance in Increase the proportion of requests that are served directly from the CloudFront caches (cache hit ratio). To learn about adding and removing the content that you want CloudFront to serve, see Add, remove, or replace content that CloudFront distributes. Topics • Increase the proportion of requests that are served directly from the CloudFront caches (cache hit ratio) • Using Amazon CloudFront Origin Shield • Optimize high availability with CloudFront origin failover • Manage how long content stays in the cache (expiration) • Cache content based on query string parameters • Cache content based on cookies • Cache content based on request headers 165 Amazon CloudFront Developer Guide Increase the proportion of requests that are served directly from the CloudFront caches (cache hit ratio) You can improve performance by increasing the proportion of your viewer requests that are served directly from the CloudFront cache instead of going to your origin servers for content. This is known as improving the cache hit ratio. The following sections explain how to improve your cache hit ratio. Topics • Specify how long CloudFront caches your objects • Use Origin Shield • Caching based on query string parameters • Caching based on cookie values • Caching based on request headers • Remove Accept-Encoding header when compression is not needed • Serve media content over HTTP Specify how long CloudFront caches your objects To increase your cache hit ratio, you can configure your origin to add a Cache-Control max-age directive to your objects, and specify the longest practical value for max-age. The shorter the cache duration, the more frequently CloudFront sends requests to your origin to determine if an object has changed and to get the latest version. You can supplement max-age with the stale-while-revalidate and stale-if-error directives to further improve cache hit ratio under certain conditions. For more information, see Manage how long content stays in the cache (expiration). Use Origin Shield CloudFront Origin Shield can help improve the cache hit ratio of your CloudFront distribution, because it provides an additional layer of caching in front of your origin. When you use Origin Shield, all requests from all of CloudFront’s caching layers to your origin come from a single location. CloudFront can retrieve each object using a single origin request from Origin Shield, and Improve your cache hit ratio 166 Amazon CloudFront Developer Guide all other layers of the CloudFront cache (edge locations and regional edge caches) can retrieve the object from Origin Shield. For more information, see Using Amazon CloudFront Origin Shield. Caching based on query string parameters If you configure CloudFront to cache based on query string parameters, you can improve caching if you do the following: • Configure CloudFront to forward only the query string parameters for which your origin will return unique objects. • Use the same case (uppercase or lowercase) for all instances of the same parameter. For example, if one request contains parameter1=A and another contains parameter1=a, CloudFront forwards separate requests to your origin when a request contains parameter1=A |
AmazonCloudFront_DevGuide-068 | AmazonCloudFront_DevGuide.pdf | 68 | edge caches) can retrieve the object from Origin Shield. For more information, see Using Amazon CloudFront Origin Shield. Caching based on query string parameters If you configure CloudFront to cache based on query string parameters, you can improve caching if you do the following: • Configure CloudFront to forward only the query string parameters for which your origin will return unique objects. • Use the same case (uppercase or lowercase) for all instances of the same parameter. For example, if one request contains parameter1=A and another contains parameter1=a, CloudFront forwards separate requests to your origin when a request contains parameter1=A and when a request contains parameter1=a. CloudFront then separately caches the corresponding objects returned by your origin separately even if the objects are identical. If you use just A or a, CloudFront forwards fewer requests to your origin. • List parameters in the same order. As with differences in case, if one request for an object contains the query string parameter1=a¶meter2=b and another request for the same object contains parameter2=b¶meter1=a, CloudFront forwards both requests to your origin and separately caches the corresponding objects even if they're identical. If you always use the same order for parameters, CloudFront forwards fewer requests to your origin. For more information, see Cache content based on query string parameters. If you want to review the query strings that CloudFront forwards to your origin, see the values in the cs-uri-query column of your CloudFront log files. For more information, see Standard logging (access logs). Caching based on cookie values If you configure CloudFront to cache based on cookie values, you can improve caching if you do the following: • Configure CloudFront to forward only specified cookies instead of forwarding all cookies. For the cookies that you configure CloudFront to forward to your origin, CloudFront forwards every combination of cookie name and value. It then separately caches the objects that your origin returns, even if they're all identical. Caching based on query string parameters 167 Amazon CloudFront Developer Guide For example, suppose that viewers include two cookies in every request, that each cookie has three possible values, and that all combinations of cookie values are possible. CloudFront forwards up to nine different requests to your origin for each object. If your origin returns different versions of an object based on only one of the cookies, then CloudFront is forwarding more requests to your origin than necessary and is needlessly caching multiple identical versions of the object. • Create separate cache behaviors for static and dynamic content, and configure CloudFront to forward cookies to your origin only for dynamic content. For example, suppose you have just one cache behavior for your distribution and that you're using the distribution both for dynamic content, such as .js files, and for .css files that rarely change. CloudFront caches separate versions of your .css files based on cookie values, so each CloudFront edge location forwards a request to your origin for every new cookie value or combination of cookie values. If you create a cache behavior for which the path pattern is *.css and for which CloudFront doesn't cache based on cookie values, then CloudFront forwards requests for .css files to your origin for only the first request that an edge location receives for a given .css file and for the first request after a .css file expires. • If possible, create separate cache behaviors for dynamic content when cookie values are unique for each user (such as a user ID), and dynamic content that varies based on a smaller number of unique values. For more information, see Cache content based on cookies. If you want to review the cookies that CloudFront forwards to your origin, see the values in the cs(Cookie) column of your CloudFront log files. For more information, see Standard logging (access logs). Caching based on request headers If you configure CloudFront to cache based on request headers, you can improve caching if you do the following: • Configure CloudFront to forward and cache based on only specified headers instead of forwarding and caching based on all headers. For the headers that you specify, CloudFront forwards every combination of header name and value. It then separately caches the objects that your origin returns even if they're all identical. Caching based on request headers 168 Amazon CloudFront Note Developer Guide CloudFront always forwards to your origin the headers specified in the following topics: • How CloudFront processes and forwards requests to your Amazon S3 origin server > HTTP request headers that CloudFront removes or updates • How CloudFront processes and forwards requests to your custom origin server > HTTP request headers and CloudFront behavior (custom and Amazon S3 origins) When you configure CloudFront to cache based on request headers, you don't change the headers that CloudFront forwards, only whether CloudFront |
AmazonCloudFront_DevGuide-069 | AmazonCloudFront_DevGuide.pdf | 69 | that your origin returns even if they're all identical. Caching based on request headers 168 Amazon CloudFront Note Developer Guide CloudFront always forwards to your origin the headers specified in the following topics: • How CloudFront processes and forwards requests to your Amazon S3 origin server > HTTP request headers that CloudFront removes or updates • How CloudFront processes and forwards requests to your custom origin server > HTTP request headers and CloudFront behavior (custom and Amazon S3 origins) When you configure CloudFront to cache based on request headers, you don't change the headers that CloudFront forwards, only whether CloudFront caches objects based on the header values. • Try to avoid caching based on request headers that have large numbers of unique values. For example, if you want to serve different sizes of an image based on the user's device, then don't configure CloudFront to cache based on the User-Agent header, which has an enormous number of possible values. Instead, configure CloudFront to cache based on the CloudFront device-type headers CloudFront-Is-Desktop-Viewer, CloudFront-Is-Mobile-Viewer, CloudFront-Is-SmartTV-Viewer, and CloudFront-Is-Tablet-Viewer. In addition, if you're returning the same version of the image for tablets and desktops, then forward only the CloudFront-Is-Tablet-Viewer header, not the CloudFront-Is-Desktop-Viewer header. For more information, see Cache content based on request headers. Remove Accept-Encoding header when compression is not needed If compression is not enabled—because the origin doesn’t support it, CloudFront doesn’t support it, or the content is not compressible—you can increase the cache hit ratio by associating a cache behavior in your distribution to an origin that sets the Custom Origin Header as follows: • Header name: Accept-Encoding • Header value: (Keep blank) Remove Accept-Encoding header when compression is not needed 169 Amazon CloudFront Developer Guide When you use this configuration, CloudFront removes the Accept-Encoding header from the cache key and doesn’t include the header in origin requests. This configuration applies to all content that CloudFront serves with the distribution from that origin. Serve media content over HTTP For information about optimizing video on demand (VOD) and streaming video content, see Video on demand and live streaming video with CloudFront. Using Amazon CloudFront Origin Shield CloudFront Origin Shield is an additional layer in the CloudFront caching infrastructure that helps to minimize your origin’s load, improve its availability, and reduce its operating costs. With CloudFront Origin Shield, you get the following benefits: Better cache hit ratio Origin Shield can help improve the cache hit ratio of your CloudFront distribution because it provides an additional layer of caching in front of your origin. When you use Origin Shield, all requests from all of CloudFront’s caching layers to your origin go through Origin Shield, increasing the likelihood of a cache hit. CloudFront can retrieve each object with a single origin request from Origin Shield to your origin, and all other layers of the CloudFront cache (edge locations and regional edge caches) can retrieve the object from Origin Shield. Reduced origin load Origin Shield can further reduce the number of simultaneous requests that are sent to your origin for the same object. Requests for content that is not in Origin Shield’s cache are consolidated with other requests for the same object, resulting in as few as one request going to your origin. Handling fewer requests at your origin can preserve your origin’s availability during peak loads or unexpected traffic spikes, and can reduce costs for things like just-in-time packaging, image transformations, and data transfer out (DTO). Better network performance When you enable Origin Shield in the AWS Region that has the lowest latency to your origin, you can get better network performance. For origins in an AWS Region, CloudFront network traffic remains on the high throughput CloudFront network all the way to your origin. For origins outside of AWS, CloudFront network traffic remains on the CloudFront network all the way to Origin Shield, which has a low latency connection to your origin. Serve media content over HTTP 170 Amazon CloudFront Developer Guide You incur additional charges for using Origin Shield. For more information, see CloudFront Pricing. Note Origin Shield isn't supported with gRPC requests. If a distribution that supports gRPC has Origin Shield enabled, the gRPC requests will continue to work. However, the requests will be proxied directly to the gRPC origin without going through Origin Shield. For more information, see Using gRPC with CloudFront distributions. Topics • Use cases for Origin Shield • Choosing the AWS Region for Origin Shield • Enabling Origin Shield • Estimating Origin Shield costs • Origin Shield high availability • How Origin Shield interacts with other CloudFront features Use cases for Origin Shield CloudFront Origin Shield can be beneficial for many use cases, including the following: • Viewers that are spread across different geographical regions • Origins that provide just-in-time packaging for live streaming or on-the-fly image processing • |
AmazonCloudFront_DevGuide-070 | AmazonCloudFront_DevGuide.pdf | 70 | be proxied directly to the gRPC origin without going through Origin Shield. For more information, see Using gRPC with CloudFront distributions. Topics • Use cases for Origin Shield • Choosing the AWS Region for Origin Shield • Enabling Origin Shield • Estimating Origin Shield costs • Origin Shield high availability • How Origin Shield interacts with other CloudFront features Use cases for Origin Shield CloudFront Origin Shield can be beneficial for many use cases, including the following: • Viewers that are spread across different geographical regions • Origins that provide just-in-time packaging for live streaming or on-the-fly image processing • On-premises origins with capacity or bandwidth constraints • Workloads that use multiple content delivery networks (CDNs) Origin Shield may not be a good fit in other cases, such as dynamic content that is proxied to the origin, content with low cacheability, or content that is infrequently requested. The following sections explain the benefits of Origin Shield for the following use cases. Use Cases • Viewers in different geographical regions • Multiple CDNs Use cases for Origin Shield 171 Amazon CloudFront Developer Guide Viewers in different geographical regions With Amazon CloudFront, you inherently get a reduced load on your origin because requests that CloudFront can serve from the cache don’t go to your origin. In addition to CloudFront’s global network of edge locations, regional edge caches serve as a mid-tier caching layer to provide cache hits and consolidate origin requests for viewers in nearby geographical regions. Viewer requests are routed first to a nearby CloudFront edge location, and if the object isn’t cached in that location, the request is sent on to a regional edge cache. When viewers are in different geographical regions, requests can be routed through different regional edge caches, each of which can send a request to your origin for the same content. But with Origin Shield, you get an additional layer of caching between the regional edge caches and your origin. All requests from all regional edge caches go through Origin Shield, further reducing the load on your origin. The following diagrams illustrate this. In the following diagrams, the origin is AWS Elemental MediaPackage. Without Origin Shield Without Origin Shield, your origin might receive duplicate requests for the same content, as shown in the following diagram. Use cases for Origin Shield 172 Amazon CloudFront With Origin Shield Developer Guide Using Origin Shield can help reduce the load on your origin, as shown in the following diagram. Multiple CDNs To serve live video events or popular on-demand content, you might use multiple content delivery networks (CDNs). Using multiple CDNs can offer certain advantages, but it also means that your origin might receive many duplicate requests for the same content, each coming from different CDNs or different locations within the same CDN. These redundant requests might adversely affect the availability of your origin or cause additional operating costs for processes like just-in-time packaging or data transfer out (DTO) to the internet. When you combine Origin Shield with using your CloudFront distribution as the origin for other CDNs, you can get the following benefits: • Fewer redundant requests received at your origin, which helps to reduce the negative effects of using multiple CDNs. • A common cache key across CDNs, and centralized management for origin-facing features. • Improved network performance. Network traffic from other CDNs is terminated at a nearby CloudFront edge location, which might provide a hit from the local cache. If the requested object Use cases for Origin Shield 173 Amazon CloudFront Developer Guide is not in the edge location cache, the request to the origin remains on the CloudFront network all the way to Origin Shield, which provides high throughput and low latency to the origin. If the requested object is in Origin Shield’s cache, the request to your origin is avoided entirely. Important If you are interested in using Origin Shield in a multi-CDN architecture, and have discounted pricing, contact us or your AWS sales representative for more information. Additional charges may apply. The following diagrams show how this configuration can help minimize the load on your origin when you serve popular live video events with multiple CDNs. In the following diagrams, the origin is AWS Elemental MediaPackage. Without Origin Shield (multiple CDNs) Without Origin Shield, your origin might receive many duplicate requests for the same content, each coming from a different CDN, as shown in the following diagram. Use cases for Origin Shield 174 Amazon CloudFront Developer Guide With Origin Shield (multiple CDNs) Using Origin Shield, with CloudFront as the origin for your other CDNs, can help reduce the load on your origin, as shown in the following diagram. Use cases for Origin Shield 175 Amazon CloudFront Developer Guide Choosing the AWS Region for Origin Shield Amazon CloudFront offers Origin Shield in AWS Regions where |
AmazonCloudFront_DevGuide-071 | AmazonCloudFront_DevGuide.pdf | 71 | Elemental MediaPackage. Without Origin Shield (multiple CDNs) Without Origin Shield, your origin might receive many duplicate requests for the same content, each coming from a different CDN, as shown in the following diagram. Use cases for Origin Shield 174 Amazon CloudFront Developer Guide With Origin Shield (multiple CDNs) Using Origin Shield, with CloudFront as the origin for your other CDNs, can help reduce the load on your origin, as shown in the following diagram. Use cases for Origin Shield 175 Amazon CloudFront Developer Guide Choosing the AWS Region for Origin Shield Amazon CloudFront offers Origin Shield in AWS Regions where CloudFront has a regional edge cache. When you enable Origin Shield, you choose the AWS Region for Origin Shield. You should choose the AWS Region that has the lowest latency to your origin. You can use Origin Shield with origins that are in an AWS Region, and with origins that are not in AWS. For origins in an AWS Region If your origin is in an AWS Region, first determine whether your origin is in a Region in which CloudFront offers Origin Shield. CloudFront offers Origin Shield in the following AWS Regions. • US East (Ohio) – us-east-2 • US East (N. Virginia) – us-east-1 • US West (Oregon) – us-west-2 • Asia Pacific (Mumbai) – ap-south-1 • Asia Pacific (Seoul) – ap-northeast-2 • Asia Pacific (Singapore) – ap-southeast-1 • Asia Pacific (Sydney) – ap-southeast-2 • Asia Pacific (Tokyo) – ap-northeast-1 • Europe (Frankfurt) – eu-central-1 • Europe (Ireland) – eu-west-1 Choosing the AWS Region for Origin Shield 176 Amazon CloudFront Developer Guide • Europe (London) – eu-west-2 • South America (São Paulo) – sa-east-1 • Middle East (UAE) – me-central-1 If your origin is in an AWS Region in which CloudFront offers Origin Shield If your origin is in an AWS Region in which CloudFront offers Origin Shield (see the preceding list), enable Origin Shield in the same Region as your origin. If your origin is not in an AWS Region in which CloudFront offers Origin Shield If your origin is not in an AWS Region in which CloudFront offers Origin Shield, see the following table to determine which Region to enable Origin Shield in. If your origin is in ... Enable Origin Shield in ... US West (N. California) – us-west-1 US West (Oregon) – us-west-2 Africa (Cape Town) – af-south-1 Europe (Ireland) – eu-west-1 Asia Pacific (Hong Kong) – ap-east-1 Asia Pacific (Singapore) – ap-southeast-1 Canada (Central) – ca-central-1 US East (N. Virginia) – us-east-1 Europe (Milan) – eu-south-1 Europe (Frankfurt) – eu-central-1 Europe (Paris) – eu-west-3 Europe (London) – eu-west-2 Europe (Stockholm) – eu-north-1 Europe (London) – eu-west-2 Middle East (Bahrain) – me-south-1 Asia Pacific (Mumbai) – ap-south-1 For origins outside of AWS You can use Origin Shield with an origin that is on-premises or is not in an AWS Region. In this case, enable Origin Shield in the AWS Region that has the lowest latency to your origin. If you’re not sure which AWS Region has the lowest latency to your origin, you can use the following suggestions to help you make a determination. Choosing the AWS Region for Origin Shield 177 Amazon CloudFront Developer Guide • You can consult the preceding table for an approximation of which AWS Region might have the lowest latency to your origin, based on your origin’s geographic location. • You can launch Amazon EC2 instances in a few different AWS Regions that are geographically close to your origin, and run some tests using ping to measure the typical network latencies between those Regions and your origin. Enabling Origin Shield You can enable Origin Shield to improve your cache hit ratio, reduce the load on your origin, and help improve performance. To enable Origin Shield, change the origin settings in a CloudFront distribution. Origin Shield is a property of the origin. For each origin in your CloudFront distributions, you can separately enable Origin Shield in whichever AWS Region provides the best performance for that origin. You can enable Origin Shield in the CloudFront console, with AWS CloudFormation, or with the CloudFront API. Console To enable Origin Shield for an existing origin (console) 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose the distribution that has the origin that you want to update. 3. Choose the Origins and Origin Groups tab. 4. Choose the origin to update, then choose Edit. 5. 6. For Enable Origin Shield, choose Yes. For Origin Shield Region, choose the AWS Region where you want to enable Origin Shield. For help choosing a Region, see Choosing the AWS Region for Origin Shield. 7. At the bottom of the page, choose Yes, Edit. When your distribution status is Deployed, Origin Shield is ready. This takes a few minutes. To |
AmazonCloudFront_DevGuide-072 | AmazonCloudFront_DevGuide.pdf | 72 | and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose the distribution that has the origin that you want to update. 3. Choose the Origins and Origin Groups tab. 4. Choose the origin to update, then choose Edit. 5. 6. For Enable Origin Shield, choose Yes. For Origin Shield Region, choose the AWS Region where you want to enable Origin Shield. For help choosing a Region, see Choosing the AWS Region for Origin Shield. 7. At the bottom of the page, choose Yes, Edit. When your distribution status is Deployed, Origin Shield is ready. This takes a few minutes. To enable Origin Shield for a new origin (console) 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. Enabling Origin Shield 178 Amazon CloudFront Developer Guide 2. To create the new origin in an existing distribution, do the following: 1. Choose the distribution where you want to create the origin. 2. Choose Create Origin, and then proceed to step 3. To create the new origin in a new distribution, do the following: 1. Choose Create Distribution. 2. In the Web section, choose Get Started. In the Origin Settings section, complete the following steps, starting with step 3. For Enable Origin Shield, choose Yes. For Origin Shield Region, choose the AWS Region where you want to enable Origin Shield. For help choosing a Region, see Choosing the AWS Region for Origin Shield. 3. 4. If you are creating a new distribution, continue configuring your distribution, using the other settings on the page. For more information, see Distribution settings reference. 5. Make sure to save your changes by choosing Create (for a new origin in an existing distribution) or Create Distribution (for a new origin in a new distribution). When your distribution status is Deployed, Origin Shield is ready. This takes a few minutes. AWS CloudFormation To enable Origin Shield with AWS CloudFormation, use the OriginShield property in the Origin property type in an AWS::CloudFront::Distribution resource. You can add the OriginShield property to an existing Origin, or include it when you create a new Origin. The following example shows the syntax, in YAML format, for enabling OriginShield in the US West (Oregon) Region (us-west-2). For help choosing a Region, see the section called “Choosing the AWS Region for Origin Shield”. This example shows only the Origin property type, not the entire AWS::CloudFront::Distribution resource. Origins: - DomainName: 3ae97e9482b0d011.mediapackage.us-west-2.amazonaws.com Id: Example-EMP-3ae97e9482b0d011 OriginShield: Enabled: true OriginShieldRegion: us-west-2 Enabling Origin Shield 179 Amazon CloudFront Developer Guide CustomOriginConfig: OriginProtocolPolicy: match-viewer OriginSSLProtocols: TLSv1 For more information, see AWS::CloudFront::Distribution Origin in the resource and property reference section of the AWS CloudFormation User Guide. API To enable Origin Shield with the CloudFront API using the AWS SDKs or AWS Command Line Interface (AWS CLI), use the OriginShield type. You specify OriginShield in an Origin, in a DistributionConfig. For information about the OriginShield type, see the following information in the Amazon CloudFront API Reference. • OriginShield (type) • Origin (type) • DistributionConfig (type) • UpdateDistribution (operation) • CreateDistribution (operation) The specific syntax for using these types and operations varies based on the SDK, CLI, or API client. For more information, see the reference documentation for your SDK, CLI, or client. Estimating Origin Shield costs You accrue charges for Origin Shield based on the number of requests that go to Origin Shield as an incremental layer. For dynamic (non-cacheable) requests that are proxied to the origin, Origin Shield is always an incremental layer. Dynamic requests use the HTTP methods PUT, POST, PATCH, and DELETE. GET and HEAD requests that have a time to live (TTL) setting of less than 3600 seconds are considered dynamic requests. In addition, GET and HEAD requests that have disabled caching are also considered dynamic requests. To estimate your charges for Origin Shield for dynamic requests, use the following formula: Total number of dynamic requests x Origin Shield charge per 10,000 requests / 10,000 Estimating Origin Shield costs 180 Amazon CloudFront Developer Guide For non-dynamic requests with the HTTP methods GET, HEAD, and OPTIONS, Origin Shield is sometimes an incremental layer. When you enable Origin Shield, you choose the AWS Region for Origin Shield. For requests that naturally go to the regional edge cache in the same Region as Origin Shield, Origin Shield is not an incremental layer. You don't accrue Origin Shield charges for these requests. For requests that go to a regional edge cache in a different Region from Origin Shield, and then go to Origin Shield, Origin Shield is an incremental layer. You do accrue Origin Shield charges for these requests. To estimate your charges for Origin Shield for cacheable requests, use the following formula: Total number of cacheable requests x (1 – cache hit rate) x percentage of requests that go to Origin Shield from a regional edge |
AmazonCloudFront_DevGuide-073 | AmazonCloudFront_DevGuide.pdf | 73 | edge cache in the same Region as Origin Shield, Origin Shield is not an incremental layer. You don't accrue Origin Shield charges for these requests. For requests that go to a regional edge cache in a different Region from Origin Shield, and then go to Origin Shield, Origin Shield is an incremental layer. You do accrue Origin Shield charges for these requests. To estimate your charges for Origin Shield for cacheable requests, use the following formula: Total number of cacheable requests x (1 – cache hit rate) x percentage of requests that go to Origin Shield from a regional edge cache in a different region x Origin Shield charge per 10,000 requests / 10,000 For more information about the charge per 10,000 requests for Origin Shield, see CloudFront Pricing. Origin Shield high availability Origin Shield leverages the CloudFront regional edge caches feature. Each of these edge caches is built in an AWS Region using at least three Availability Zones with fleets of auto-scaling Amazon EC2 instances. Connections from CloudFront locations to Origin Shield also use active error tracking for each request to automatically route the request to a secondary Origin Shield location if the primary Origin Shield location is unavailable. How Origin Shield interacts with other CloudFront features The following sections explain how Origin Shield interacts with other CloudFront features. Origin Shield and CloudFront logging To see when Origin Shield handled a request, you must enable one of the following: • CloudFront standard logs (access logs). Standard logs are provided free of charge. • CloudFront real-time logs. You incur additional charges for using real-time logs. See Amazon CloudFront Pricing. Cache hits from Origin Shield appear as OriginShieldHit in the x-edge-detailed-result- type field in CloudFront logs. Origin Shield leverages Amazon CloudFront’s regional edge caches. Origin Shield high availability 181 Amazon CloudFront Developer Guide If a request is routed from a CloudFront edge location to the regional edge cache that is acting as Origin Shield, it is reported as a Hit in the logs, not as an OriginShieldHit. Origin Shield and origin groups Origin Shield is compatible with CloudFront origin groups. Because Origin Shield is a property of the origin, requests always travel through Origin Shield for each origin even when the origin is part of an origin group. For a given request, CloudFront routes the request to the primary origin in the origin group through the primary origin’s Origin Shield. If that request fails (according to the origin group failover criteria), CloudFront routes the request to the secondary origin through the secondary origin’s Origin Shield. Origin Shield and Lambda@Edge Origin Shield does not impact the functionality of Lambda@Edge functions, but it can affect the AWS Region where those functions run. When you use Origin Shield with Lambda@Edge, origin-facing triggers (origin request and origin response) run in the AWS Region where Origin Shield is enabled. If the primary Origin Shield location is unavailable and CloudFront routes requests to a secondary Origin Shield location, Lambda@Edge origin-facing triggers will also shift to use the secondary Origin Shield location. Viewer-facing triggers are not affected. Optimize high availability with CloudFront origin failover You can set up CloudFront with origin failover for scenarios that require high availability. To get started, you create an origin group with two origins: a primary and a secondary. If the primary origin is unavailable, or returns specific HTTP response status codes that indicate a failure, CloudFront automatically switches to the secondary origin. To set up origin failover, you must have a distribution with at least two origins. Next, you create an origin group for your distribution that includes two origins, setting one as the primary. Finally, you create or update a cache behavior to use the origin group. To see the steps for setting up origin groups and configuring specific origin failover options, see Create an origin group. After you configure origin failover for a cache behavior, CloudFront does the following for viewer requests: Increase availability with origin failover 182 Amazon CloudFront Developer Guide • When there’s a cache hit, CloudFront returns the requested object. • When there’s a cache miss, CloudFront routes the request to the primary origin in the origin group. • When the primary origin returns a status code that is not configured for failover, such as an HTTP 2xx or 3xx status code, CloudFront serves the requested object to the viewer. • When any of the following occur: • The primary origin returns an HTTP status code that you’ve configured for failover • CloudFront fails to connect to the primary origin (when 503 is set as a failover code) • The response from the primary origin takes too long (times out) (when 504 is set as a failover code) Then CloudFront routes the request to the secondary origin in the origin group. Note For some use cases, like |
AmazonCloudFront_DevGuide-074 | AmazonCloudFront_DevGuide.pdf | 74 | that is not configured for failover, such as an HTTP 2xx or 3xx status code, CloudFront serves the requested object to the viewer. • When any of the following occur: • The primary origin returns an HTTP status code that you’ve configured for failover • CloudFront fails to connect to the primary origin (when 503 is set as a failover code) • The response from the primary origin takes too long (times out) (when 504 is set as a failover code) Then CloudFront routes the request to the secondary origin in the origin group. Note For some use cases, like streaming video content, you might want CloudFront to fail over to the secondary origin quickly. To adjust how quickly CloudFront fails over to the secondary origin, see Control origin timeouts and attempts. 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. CloudFront fails over to the secondary origin only when the HTTP method of the viewer request is GET, HEAD, or OPTIONS. CloudFront does not fail over when the viewer sends a different HTTP method (for example POST, PUT, and so on). The following diagram illustrates how origin failover works. Increase availability with origin failover 183 Amazon CloudFront Developer Guide Topics • Create an origin group • Control origin timeouts and attempts • Use origin failover with Lambda@Edge functions • Use custom error pages with origin failover Create an origin group To create an origin group 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose the distribution that you want to create the origin group for. 3. Choose the Origins tab. 4. Make sure the distribution has more than one origin. If it doesn’t, add a second origin. 5. On the Origins tab, in the Origin groups pane, choose Create origin group. 6. Choose the origins for the origin group. After you add origins, use the arrows to set the priority —that is, which origin is primary and which is secondary. Create an origin group 184 Amazon CloudFront Developer Guide 7. Enter a name for the origin group. 8. Choose the HTTP status codes to use as failover criteria. You can choose any combination of the following status codes: 400, 403, 404, 416, 500, 502, 503, or 504. When CloudFront receives a response with one of the status codes that you specify, it fails over to the secondary origin. Note CloudFront fails over to the secondary origin only when the HTTP method of the viewer request is GET, HEAD, or OPTIONS. CloudFront does not fail over when the viewer sends a different HTTP method (for example POST, PUT, and so on). 9. Under Origin selection criteria, specify how your origins are selected when your distribution routes viewer requests. You can choose the following options. Default CloudFront will use the default origin priority that you specify on the Settings page. Media quality score CloudFront tracks and uses this score to determine the first origin to forward the request to. This also authorizes CloudFront to make asynchronous HEAD requests to the alternate origin in the origin group to determine its media quality score. You can only choose this option for AWS Elemental MediaPackage v2 origins. For more information, see Media quality-aware resiliency. 10. Choose Create origin group. Make sure to assign your origin group as the origin for your distribution's cache behavior. For more information, see Name. Control origin timeouts and attempts By default, CloudFront tries to connect to the primary origin in an origin group for as long as 30 seconds (3 connection attempts of 10 seconds each) before failing over to the secondary origin. For some use cases, like streaming video content, you might want CloudFront to fail over to the secondary origin more quickly. You can adjust the following settings to affect how quickly CloudFront fails over to the secondary origin. If the origin is a secondary origin, or an origin that Control origin timeouts and attempts 185 Amazon CloudFront Developer Guide is not part of an origin group, these settings affect how quickly CloudFront returns an HTTP 504 response to the viewer. To fail over more quickly, specify a shorter connection timeout, fewer connection attempts, or both. For custom origins (including Amazon S3 bucket origins that are configured with static website hosting), you can also adjust the origin response timeout. Origin connection timeout The origin connection timeout setting affects how long CloudFront waits when trying to establish a connection to the origin. By default, CloudFront waits 10 seconds to establish a connection, but you can specify 1–10 seconds (inclusive). For more information, see Connection timeout. Origin connection attempts The origin connection attempts |
AmazonCloudFront_DevGuide-075 | AmazonCloudFront_DevGuide.pdf | 75 | quickly CloudFront returns an HTTP 504 response to the viewer. To fail over more quickly, specify a shorter connection timeout, fewer connection attempts, or both. For custom origins (including Amazon S3 bucket origins that are configured with static website hosting), you can also adjust the origin response timeout. Origin connection timeout The origin connection timeout setting affects how long CloudFront waits when trying to establish a connection to the origin. By default, CloudFront waits 10 seconds to establish a connection, but you can specify 1–10 seconds (inclusive). For more information, see Connection timeout. Origin connection attempts The origin connection attempts setting affects the number of times that CloudFront attempts to connect to the origin. By default, CloudFront tries 3 times to connect, but you can specify 1– 3 (inclusive). For more information, see Connection attempts. For a custom origin (including an Amazon S3 bucket that’s configured with static website hosting), this setting also affects the number of times that CloudFront attempts to get a response from the origin in the case of an origin response timeout. Origin response timeout Note This applies only to custom origins. The origin response timeout setting affects how long CloudFront waits to receive a response (or to receive the complete response) from the origin. By default, CloudFront waits for 30 seconds, but you can specify 1–60 seconds (inclusive). For more information, see Response timeout (custom and VPC origins only). How to change these settings To change these settings in the CloudFront console • For a new origin or a new distribution, you specify these values when you create the resource. Control origin timeouts and attempts 186 Amazon CloudFront Developer Guide • For an existing origin in an existing distribution, you specify these values when you edit the origin. For more information, see Distribution settings reference. Use origin failover with Lambda@Edge functions You can use Lambda@Edge functions with CloudFront distributions that you’ve set up with origin groups. To use a Lambda function, specify it in an origin request or origin response trigger for an origin group when you create the cache behavior. When you use a Lambda@Edge function with an origin group, the function can be triggered twice for a single viewer request. For example, consider this scenario: 1. You create a Lambda@Edge function with an origin request trigger. 2. The Lambda function is triggered once when CloudFront sends a request to the primary origin (on a cache miss). 3. The primary origin responds with an HTTP status code that’s configured for failover. 4. The Lambda function is triggered again when CloudFront sends the same request to the secondary origin. The following diagram illustrates how origin failover works when you include a Lambda@Edge function in an origin request or response trigger. Use origin failover with Lambda@Edge functions 187 Amazon CloudFront Developer Guide For more information about using Lambda@Edge triggers, see the section called “Add triggers for a Lambda@Edge function”. For more information about managing DNS failover, see Configuring DNS failover in the Amazon Route 53 Developer Guide. Use custom error pages with origin failover You can use custom error pages with origin groups similarly to how you use them with origins that are not set up for origin failover. When you use origin failover, you can configure CloudFront to return a custom error page for the primary or secondary origin (or both): • Return a custom error page for the primary origin – If the primary origin returns an HTTP status code that’s not configured for failover, CloudFront returns the custom error page to viewers. • Return a custom error page for the secondary origin – If CloudFront receives a failure status code from the secondary origin, CloudFront returns the custom error page. Use custom error pages with origin failover 188 Amazon CloudFront Developer Guide For more information about using custom error pages with CloudFront, see Generate custom error responses. Manage how long content stays in the cache (expiration) You can control how long your files stay in a CloudFront cache before CloudFront forwards another request to your origin. Reducing the duration allows you to serve dynamic content. Increasing the duration means that your users get better performance because your files are more likely to be served directly from the edge cache. A longer duration also reduces the load on your origin. Typically, CloudFront serves a file from an edge location until the cache duration that you specified passes—that is, until the file expires. After it expires, the next time the edge location gets a request for the file, CloudFront forwards the request to the origin to verify that the cache contains the latest version of the file. The response from the origin depends on whether the file has changed: • If the CloudFront cache already has the latest version, the origin returns a status code |
AmazonCloudFront_DevGuide-076 | AmazonCloudFront_DevGuide.pdf | 76 | served directly from the edge cache. A longer duration also reduces the load on your origin. Typically, CloudFront serves a file from an edge location until the cache duration that you specified passes—that is, until the file expires. After it expires, the next time the edge location gets a request for the file, CloudFront forwards the request to the origin to verify that the cache contains the latest version of the file. The response from the origin depends on whether the file has changed: • If the CloudFront cache already has the latest version, the origin returns a status code 304 Not Modified. • If the CloudFront cache does not have the latest version, the origin returns a status code 200 OK and the latest version of the file. If a file in an edge location isn't frequently requested, CloudFront might evict the file—remove the file before its expiration date—to make room for files that have been requested more recently. We recommend managing your cache duration by updating your distribution's cache policy. If you opt out of using a cache policy, the default TTL (Time to Live) is 24 hours, but you can update the following settings to override the default: • To change the cache duration for all files that match the same path pattern, you can change the CloudFront settings for Minimum TTL, Maximum TTL, and Default TTL for a cache behavior. For information about the individual settings, see Minimum TTL, Maximum TTL, and Default TTL in the section called “Distribution settings”. • To change the cache duration for an individual file, you can configure your origin to add a Cache-Control header with the max-age or s-maxage directive, or an Expires header to the file. For more information, see Use headers to control cache duration for individual objects. Manage cache expiration 189 Amazon CloudFront Developer Guide For more information about how Minimum TTL, Default TTL, and Maximum TTL interact with the max-age and s-maxage directives and the Expires header field, see the section called “Specify the amount of time that CloudFront caches objects”. You can also control how long errors (for example, 404 Not Found) stay in a CloudFront cache before CloudFront tries again to get the requested object by forwarding another request to your origin. For more information, see the section called “How CloudFront processes HTTP 4xx and 5xx status codes from your origin”. Topics • Use headers to control cache duration for individual objects • Serve stale (expired) content • Specify the amount of time that CloudFront caches objects • Add headers to your objects by using the Amazon S3 console Use headers to control cache duration for individual objects You can use the Cache-Control and Expires headers to control how long objects stay in the cache. Settings for Minimum TTL, Default TTL, and Maximum TTL also affect cache duration, but here's an overview of how headers can affect cache duration: • The Cache-Control max-age directive lets you specify how long (in seconds) that you want an object to remain in the cache before CloudFront gets the object again from the origin server. The minimum expiration time CloudFront supports is 0 seconds. The maximum value is 100 years. Specify the value in the following format: Cache-Control: max-age=seconds For example, the following directive tells CloudFront to keep the associated object in the cache for 3600 seconds (one hour): Cache-Control: max-age=3600 If you want objects to stay in CloudFront edge caches for a different duration than they stay in browser caches, you can use the Cache-Control max-age and Cache-Control s-maxage directives together. For more information, see Specify the amount of time that CloudFront caches objects. Use headers to control cache duration for individual objects 190 Amazon CloudFront Developer Guide • The Expires header field lets you specify an expiration date and time using the format specified in RFC 2616, Hypertext Transfer Protocol -- HTTP/1.1 Section 3.3.1, Full Date, for example: Sat, 27 Jun 2015 23:59:59 GMT We recommend that you use the Cache-Control max-age directive instead of the Expires header field to control object caching. If you specify values both for Cache-Control max-age and for Expires, CloudFront uses only the value of Cache-Control max-age. For more information, see Specify the amount of time that CloudFront caches objects. You cannot use the HTTP Cache-Control or Pragma header fields in a GET request from a viewer to force CloudFront to go back to the origin server for the object. CloudFront ignores those header fields in viewer requests. For more information about the Cache-Control and Expires header fields, see the following sections in RFC 2616, Hypertext Transfer Protocol -- HTTP/1.1: • Section 14.9 Cache Control • Section 14.21 Expires Serve stale (expired) content CloudFront supports the Stale-While-Revalidate and Stale-If-Error cache control directives. You can use these directives to specify how long |
AmazonCloudFront_DevGuide-077 | AmazonCloudFront_DevGuide.pdf | 77 | Specify the amount of time that CloudFront caches objects. You cannot use the HTTP Cache-Control or Pragma header fields in a GET request from a viewer to force CloudFront to go back to the origin server for the object. CloudFront ignores those header fields in viewer requests. For more information about the Cache-Control and Expires header fields, see the following sections in RFC 2616, Hypertext Transfer Protocol -- HTTP/1.1: • Section 14.9 Cache Control • Section 14.21 Expires Serve stale (expired) content CloudFront supports the Stale-While-Revalidate and Stale-If-Error cache control directives. You can use these directives to specify how long stale content is available for viewers. Topics • Stale-While-Revalidate • Stale-If-Error • Use both directives Stale-While-Revalidate This directive allows CloudFront to serve stale content from the cache while CloudFront asynchronously fetches a fresh version from the origin. This improves latency as viewers receive responses immediately from edge locations without having to wait for the background fetch. Fresh content is loaded in the background for future requests. Serve stale (expired) content 191 Amazon CloudFront Developer Guide Example Example: Stale-While-Revalidate CloudFront does the following when you set the Cache-Control header to use these directives. Cache-Control: max-age=3600, stale-while-revalidate=600 1. CloudFront will cache a response for one hour (max-age=3600). 2. If a request is made after this duration, CloudFront serves the stale content, while concurrently sending a request to the origin to revalidate and refresh the cached content. 3. While the content is being revalidated, CloudFront serves the stale content up to 10 minutes (stale-while-revalidate=600). Note CloudFront will serve the stale content up to the value of the stale-while-revalidate directive or the value of the CloudFront maximum TTL, whichever is less. After the maximum TTL duration, the stale object won't be available from the edge cache, regardless of the stale-while-revalidate value. Stale-If-Error This directive allows CloudFront to serve stale content from the cache if the origin is unreachable or returns an error code that is between 500 and 600. This ensures that viewers can access content even during an origin outage. Example Example: Stale-If-Error CloudFront does the following when you set the Cache-Control header to use these directives. Cache-Control: max-age=3600, stale-if-error=86400 1. CloudFront caches the response for one hour (max-age=3600). 2. If the origin is down or returns an error after this duration, CloudFront continues to serve the stale content for up to 24 hours (stale-if-error=86400) 3. If you configured custom error responses, CloudFront will attempt to serve the stale content if an error is encountered within the specified stale-if-error duration. If the stale content is Serve stale (expired) content 192 Amazon CloudFront Developer Guide unavailable, CloudFront will then serve the custom error responses that you configured for the corresponding error status code. For more information, see Generate custom error responses. Notes • CloudFront will serve the stale content up to the value of the stale-if-error directive or the value of the CloudFront maximum TTL, whichever is less. After the maximum TTL duration, the stale object won't be available from the edge cache, regardless of the stale-if-error value. • If you don't configure stale-if-error or custom error responses, CloudFront will return the stale object or forward the error response back to viewer, depending on whether the requested object is in the edge cache or not. For more information, see How CloudFront processes errors if you haven't configured custom error pages. Use both directives Both stale-while-revalidate and stale-if-error are independent cache control directives that you can use together to reduce latency and to add a buffer for your origin to respond or recover. Example Example: Using both directives CloudFront does the following when you set the Cache-Control header to use the following directives. Cache-Control: max-age=3600, stale-while-revalidate=600, stale-if-error=86400 1. CloudFront caches the response for one hour (max-age=3600). 2. If a request is made after this duration, CloudFront serves the stale content for up to 10 minutes (stale-while-revalidate=600) while the content is being revalidated. 3. If the origin server returns an error while CloudFront attempts to revalidate the content, CloudFront will continue to serve the stale content for up to 24 hours (stale-if- error=86400). Serve stale (expired) content 193 Amazon CloudFront Developer Guide Caching is a balance between performance and freshness. Using directives like stale-while- revalidate and stale-if-error can enhance performance and user experience, but make sure the configurations align with how fresh you want your content to be. Stale content directives are best suited for use cases where content needs to be refreshed but having the latest version is non-essential. Additionally, if your content doesn’t change or rarely changes, stale-while- revalidate could add unnecessary network requests. Instead, consider setting a long cache duration. Specify the amount of time that CloudFront caches objects To control the amount of time that CloudFront keeps an object in the cache before sending another request to the origin, you can: • |
AmazonCloudFront_DevGuide-078 | AmazonCloudFront_DevGuide.pdf | 78 | stale-if-error can enhance performance and user experience, but make sure the configurations align with how fresh you want your content to be. Stale content directives are best suited for use cases where content needs to be refreshed but having the latest version is non-essential. Additionally, if your content doesn’t change or rarely changes, stale-while- revalidate could add unnecessary network requests. Instead, consider setting a long cache duration. Specify the amount of time that CloudFront caches objects To control the amount of time that CloudFront keeps an object in the cache before sending another request to the origin, you can: • Set the minimum, maximum, and default TTL values in a CloudFront distribution's cache behavior. You can set these values in a cache policy attached to the cache behavior (recommended), or in the legacy cache settings. • Include the Cache-Control or Expires header in responses from the origin. These headers also help determine how long a browser keeps an object in the browser cache before sending another request to CloudFront. The following table explains how the Cache-Control and Expires headers sent from the origin work together with the TTL settings in a cache behavior to affect caching. Origin headers Minimum TTL = 0 Minimum TTL > 0 The origin adds a Cache- Control: max-age directive to the object CloudFront caching CloudFront caching CloudFront caches the object for the lesser of the value of the Cache-Control: max-age directive or the value of the CloudFront maximum TTL. CloudFront caching depends on the values of the CloudFront minimum TTL and maximum TTL and the Cache-Control max-age directive: Browser caching • If minimum TTL < max- age < maximum TTL, Specify the amount of time that CloudFront caches objects 194 Amazon CloudFront Developer Guide Origin headers Minimum TTL = 0 Minimum TTL > 0 Browsers cache the object for then CloudFront caches the the value of the Cache-Con trol: max-age directive. object for the value of the Cache-Control: max- age directive. • • If max-age < minimum TTL, then CloudFront caches the object for the value of the CloudFront minimum TTL. If max-age > maximum TTL, then CloudFront caches the object for the value of the CloudFront maximum TTL. Browser caching Browsers cache the object for the value of the Cache-Con trol: max-age directive. The origin does not add a Cache-Control: max- age directive to the object CloudFront caching CloudFront caching CloudFront caches the object for the value of the CloudFron t default TTL. CloudFront caches the object for the greater of the value of the CloudFront minimum TTL or default TTL. Browser caching Depends on the browser. Browser caching Depends on the browser. Specify the amount of time that CloudFront caches objects 195 Amazon CloudFront Developer Guide Origin headers Minimum TTL = 0 Minimum TTL > 0 The origin adds Cache- Control: max-age and Cache-Control: s- maxage directives to the object CloudFront caching CloudFront caching CloudFront caches the object CloudFront caching depends for the lesser of the value of on the values of the the Cache-Control: s- maxage directive or the value of the CloudFront maximum TTL. Browser caching Browsers cache the object for the value of the Cache-Con trol max-age directive. CloudFront minimum TTL and maximum TTL and the Cache-Control: s- maxage directive: • • • If minimum TTL < s- maxage < maximum TTL, then CloudFront caches the object for the value of the Cache-Control: s- maxage directive. If s-maxage < minimum TTL, then CloudFront caches the object for the value of the CloudFront minimum TTL. If s-maxage > maximum TTL, then CloudFront caches the object for the value of the CloudFront maximum TTL. Browser caching Browsers cache the object for the value of the Cache-Con trol: max-age directive. Specify the amount of time that CloudFront caches objects 196 Amazon CloudFront Developer Guide Origin headers Minimum TTL = 0 Minimum TTL > 0 The origin adds an Expires header to the object CloudFront caching CloudFront caching CloudFront caches the CloudFront caching depends object until the date in the on the values of the Expires header or for the value of the CloudFront maximum TTL, whichever is CloudFront minimum TTL and maximum TTL and the Expires header: sooner. Browser caching Browsers cache the object until the date in the Expires header. • • • If minimum TTL < Expires < maximum TTL, then CloudFront caches the object until the date and time in the Expires header. If Expires < minimum TTL, then CloudFront caches the object for the value of the CloudFront minimum TTL. If Expires > maximum TTL, then CloudFront caches the object for the value of the CloudFront maximum TTL. Browser caching Browsers cache the object until the date and time in the Expires header. Specify the amount of time that CloudFront caches objects 197 Amazon CloudFront Developer Guide Origin headers |
AmazonCloudFront_DevGuide-079 | AmazonCloudFront_DevGuide.pdf | 79 | object until the date in the Expires header. • • • If minimum TTL < Expires < maximum TTL, then CloudFront caches the object until the date and time in the Expires header. If Expires < minimum TTL, then CloudFront caches the object for the value of the CloudFront minimum TTL. If Expires > maximum TTL, then CloudFront caches the object for the value of the CloudFront maximum TTL. Browser caching Browsers cache the object until the date and time in the Expires header. Specify the amount of time that CloudFront caches objects 197 Amazon CloudFront Developer Guide Origin headers Minimum TTL = 0 Minimum TTL > 0 Origin adds Cache-Con trol: no-cache store, and/or private directives to the object , no- CloudFront and browsers respect the headers. CloudFront caching CloudFront caches the object for the value of the CloudFron t minimum TTL. See the warning below this table. Browser caching Browsers respect the headers. Warning If your minimum TTL is greater than 0, CloudFront uses the cache policy’s minimum TTL, even if the Cache-Control: no-cache, no-store, and/or private directives are present in the origin headers. If the origin is reachable, CloudFront gets the object from the origin and returns it to the viewer. If the origin is unreachable and the minimum or maximum TTL value is greater than 0, CloudFront will serve the object that it got from the origin previously. To avoid this behavior, include the Cache-Control: stale-if-error=0 directive with the object returned from the origin. This causes CloudFront to return an error in response to future requests if the origin is unreachable, rather than returning the object that it got from the origin previously. For information about how to change settings for distributions using the CloudFront console, see Update a distribution. For information about how to change settings for distributions using the CloudFront API, see UpdateDistribution. Add headers to your objects by using the Amazon S3 console You can add the Cache-Control or Expires header field to your Amazon S3 objects. To do so, you modify the metadata fields for the object. Add headers to your objects by using the Amazon S3 console 198 Amazon CloudFront Developer Guide To add a Cache-Control or Expires header field to Amazon S3 objects 1. 2. 3. Follow the procedure in the Replacing system-defined metadata section on the Editing object metadata in the Amazon S3 console topic in the Amazon S3 User Guide. For Key, choose the name of the header that you are adding (Cache-Control or Expires). For Value, enter a header value. For example, for a Cache-Control header, you could enter max-age=86400. For Expires, you could enter an expiration date and time such as Wed, 30 Jun 2021 09:28:00 GMT. 4. Follow the rest of the procedure to save your metadata changes. Cache content based on query string parameters Some web applications use query strings to send information to the origin. A query string is the part of a web request that appears after a ? character; the string can contain one or more parameters, separated by & characters. In the following example, the query string includes two parameters, color=red and size=large: https://d111111abcdef8.cloudfront.net/images/image.jpg?color=red&size=large For distributions, you can choose if you want CloudFront to forward query strings to your origin and whether to cache your content based on all parameters or on selected parameters. Why might this be useful? Consider the following example. Suppose that your website is available in five languages. The directory structure and file names for all five versions of the website are identical. As a user views your website, requests that are forwarded to CloudFront include a language query string parameter based on the language that the user chose. You can configure CloudFront to forward query strings to the origin and to cache based on the language parameter. If you configure your web server to return the version of a given page that corresponds with the selected language, CloudFront caches each language version separately, based on the value of the language query string parameter. In this example, if the main page for your website is main.html, the following five requests cause CloudFront to cache main.html five times, once for each value of the language query string parameter: • https://d111111abcdef8.cloudfront.net/main.html?language=de • https://d111111abcdef8.cloudfront.net/main.html?language=en Caching and query string parameters 199 Amazon CloudFront Developer Guide • https://d111111abcdef8.cloudfront.net/main.html?language=es • https://d111111abcdef8.cloudfront.net/main.html?language=fr • https://d111111abcdef8.cloudfront.net/main.html?language=jp Note the following: • Some HTTP servers don't process query string parameters and, therefore, don't return different versions of an object based on parameter values. For these origins, if you configure CloudFront to forward query string parameters to the origin, CloudFront still caches based on the parameter values even though the origin returns identical versions of the object to CloudFront for every parameter value. • For query string parameters to work as described in the example above with the |
AmazonCloudFront_DevGuide-080 | AmazonCloudFront_DevGuide.pdf | 80 | parameter: • https://d111111abcdef8.cloudfront.net/main.html?language=de • https://d111111abcdef8.cloudfront.net/main.html?language=en Caching and query string parameters 199 Amazon CloudFront Developer Guide • https://d111111abcdef8.cloudfront.net/main.html?language=es • https://d111111abcdef8.cloudfront.net/main.html?language=fr • https://d111111abcdef8.cloudfront.net/main.html?language=jp Note the following: • Some HTTP servers don't process query string parameters and, therefore, don't return different versions of an object based on parameter values. For these origins, if you configure CloudFront to forward query string parameters to the origin, CloudFront still caches based on the parameter values even though the origin returns identical versions of the object to CloudFront for every parameter value. • For query string parameters to work as described in the example above with the languages, you must use the & character as the delimiter between query string parameters. If you use a different delimiter, you may get unexpected results, depending on which parameters you specify for CloudFront to use as a basis for caching, and the order in which the parameters appear in the query string. The following examples show what happens if you use a different delimiter and you configure CloudFront to cache based only on the color parameter: • In the following request, CloudFront caches your content based on the value of the color parameter, but CloudFront interprets the value as red;size=large: https://d111111abcdef8.cloudfront.net/images/ image.jpg?color=red;size=large • In the following request, CloudFront caches your content but doesn't base caching on the query string parameters. This is because you configured CloudFront to cache based on the color parameter, but CloudFront interprets the following string as containing only a size parameter that has a value of large;color=red: https://d111111abcdef8.cloudfront.net/images/ image.jpg?size=large;color=red You can configure CloudFront to do one of the following: • Don't forward query strings to the origin at all. If you don't forward query strings, CloudFront doesn't cache based on query string parameters. Caching and query string parameters 200 Amazon CloudFront Developer Guide • Forward query strings to the origin, and cache based on all parameters in the query string. • Forward query strings to the origin, and cache based on specified parameters in the query string. For more information, see the section called “Optimize caching”. Topics • Console and API settings for query string forwarding and caching • Optimize caching • Query string parameters and CloudFront standard logs (access logs) Console and API settings for query string forwarding and caching To configure query string forwarding and caching in the CloudFront console, see the following settings in the section called “Distribution settings”: • the section called “Query string forwarding and caching” • the section called “Query string allowlist” To configure query string forwarding and caching with the CloudFront API, see CachePolicy and OriginRequestPolicy in the Amazon CloudFront API Reference. Optimize caching When you configure CloudFront to cache based on query string parameters, you can take the following steps to reduce the number of requests that CloudFront forwards to your origin. When CloudFront edge locations serve objects, you reduce the load on your origin server and reduce latency because objects are served from locations that are closer to your users. Cache based only on parameters for which your origin returns different versions of an object For each query string parameter that your web application forwards to CloudFront, CloudFront forwards requests to your origin for every parameter value and caches a separate version of the object for every parameter value. This is true even if your origin always returns the same object regardless of the parameter value. For multiple parameters, the number of requests and the number of objects multiply. Console and API settings for query string forwarding and caching 201 Amazon CloudFront Developer Guide We recommend that you configure CloudFront to cache based only on the query string parameters for which your origin returns different versions, and that you carefully consider the merits of caching based on each parameter. For example, suppose you have a retail website. You have pictures of a jacket in six different colors, and the jacket comes in 10 different sizes. The pictures that you have of the jacket show the different colors but not the different sizes. To optimize caching, you should configure CloudFront to cache based only on the color parameter, not on the size parameter. This increases the likelihood that CloudFront can serve a request from the cache, which improves performance and reduces the load on your origin. Always list parameters in the same order The order of parameters matters in query strings. In the following example, the query strings are identical except that the parameters are in a different order. This causes CloudFront to forward two separate requests for image.jpg to your origin and to cache two separate versions of the object: • https://d111111abcdef8.cloudfront.net/images/ image.jpg?color=red&size=large • https://d111111abcdef8.cloudfront.net/images/ image.jpg?size=large&color=red We recommend that you always list parameter names in the same order, such as alphabetical order. Always use the same case for parameter names and values CloudFront considers the case of |
AmazonCloudFront_DevGuide-081 | AmazonCloudFront_DevGuide.pdf | 81 | performance and reduces the load on your origin. Always list parameters in the same order The order of parameters matters in query strings. In the following example, the query strings are identical except that the parameters are in a different order. This causes CloudFront to forward two separate requests for image.jpg to your origin and to cache two separate versions of the object: • https://d111111abcdef8.cloudfront.net/images/ image.jpg?color=red&size=large • https://d111111abcdef8.cloudfront.net/images/ image.jpg?size=large&color=red We recommend that you always list parameter names in the same order, such as alphabetical order. Always use the same case for parameter names and values CloudFront considers the case of parameter names and values when caching based on query string parameters. In the following example, the query strings are identical except for the case of parameter names and values. This causes CloudFront to forward four separate requests for image.jpg to your origin and to cache four separate versions of the object: • https://d111111abcdef8.cloudfront.net/images/image.jpg?color=red • https://d111111abcdef8.cloudfront.net/images/image.jpg?color=Red • https://d111111abcdef8.cloudfront.net/images/image.jpg?Color=red • https://d111111abcdef8.cloudfront.net/images/image.jpg?Color=Red We recommend that you use case consistently for parameter names and values, such as all lowercase. Optimize caching 202 Amazon CloudFront Developer Guide Don’t use parameter names that conflict with signed URLs If you're using signed URLs to restrict access to your content (if you added trusted signers to your distribution), CloudFront removes the following query string parameters before forwarding the rest of the URL to your origin: • Expires • Key-Pair-Id • Policy • Signature If you're using signed URLs and you want to configure CloudFront to forward query strings to your origin, your own query string parameters cannot be named Expires, Key-Pair-Id, Policy, or Signature. Query string parameters and CloudFront standard logs (access logs) If you enable logging, CloudFront logs the full URL, including query string parameters. This is true regardless of whether you have configured CloudFront to forward query strings to the origin. For more information about CloudFront logging, see the section called “Standard logging (access logs)”. Cache content based on cookies By default, CloudFront doesn’t consider cookies when processing requests and responses, or when caching your objects in edge locations. If CloudFront receives two requests that are identical except for what’s in the Cookie header, then, by default, CloudFront treats the requests as identical and returns the same object for both requests. 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. When you do this, CloudFront uses some or all of the cookies in viewer requests— whichever ones it’s configured to forward—to uniquely identify an object in the cache. For example, suppose that requests for locations.html contain a country cookie that has a value of either uk or fr. When you configure CloudFront to cache your objects based on the value of the country cookie, CloudFront forwards requests for locations.html to the origin and includes the country cookie and its value. Your origin returns locations.html, and CloudFront Query string parameters and CloudFront standard logs (access logs) 203 Amazon CloudFront Developer Guide caches the object once for requests in which the value of the country cookie is uk and once for requests in which the value is fr. Important Amazon S3 and some HTTP servers don’t process cookies. Don’t configure CloudFront to forward cookies to an origin that doesn’t process cookies or doesn’t vary its response based on cookies. That can cause CloudFront to forward more requests to the origin for the same object, which slows performance and increases the load on the origin. If, considering the previous example, your origin doesn’t process the country cookie or always returns the same version of locations.html to CloudFront regardless of the value of the country cookie, don’t configure CloudFront to forward that cookie. Conversely, if your custom origin depends on a particular cookie or sends different responses based on a cookie, make sure you configure CloudFront to forward that cookie to the origin. Otherwise, CloudFront removes the cookie before forwarding the request to your origin. To configure cookie forwarding, you update your distribution’s cache behavior. For more information about cache behaviors, see Cache behavior settings, particularly the Forward cookies and Allowlist cookies sections. You can configure each cache behavior to do one of the following: • Forward all cookies to your origin – CloudFront includes all cookies sent by the viewer when it forwards requests to the origin. When your origin returns a response, CloudFront caches the response using the cookie names and values in the viewer request. If the origin response includes Set-Cookie headers, CloudFront returns them to the viewer with the requested object. CloudFront also caches the Set-Cookie headers with the object returned from the origin, and sends those Set-Cookie headers to viewers on all cache hits. • Forward a set of cookies |
AmazonCloudFront_DevGuide-082 | AmazonCloudFront_DevGuide.pdf | 82 | configure each cache behavior to do one of the following: • Forward all cookies to your origin – CloudFront includes all cookies sent by the viewer when it forwards requests to the origin. When your origin returns a response, CloudFront caches the response using the cookie names and values in the viewer request. If the origin response includes Set-Cookie headers, CloudFront returns them to the viewer with the requested object. CloudFront also caches the Set-Cookie headers with the object returned from the origin, and sends those Set-Cookie headers to viewers on all cache hits. • Forward a set of cookies that you specify – CloudFront removes any cookies that the viewer sends that aren’t on the allowlist before it forwards a request to the origin. CloudFront caches the response using the listed cookies names and values in the viewer request. If the origin response includes Set-Cookie headers, CloudFront returns them to the viewer with the requested object. CloudFront also caches the Set-Cookie headers with the object returned from the origin, and sends those Set-Cookie headers to viewers on all cache hits. For information about specifying wildcards in cookie names, see Allowlist cookies. Cache content based on cookies 204 Amazon CloudFront Developer Guide For the current quota on the number of cookie names that you can forward for each cache behavior, or to request a higher quota, see Quotas on query strings (legacy cache settings). • Don't forward cookies to your origin – CloudFront doesn’t cache your objects based on cookie sent by the viewer. In addition, CloudFront removes cookies before forwarding requests to your origin, and removes Set-Cookie headers from responses before returning responses to your viewers. Because this isn't an optimal way to use your origin resources, when you select this cache behavior, you should make sure that your origin doesn't include cookies in origin responses by default. Note the following about specifying the cookies that you want to forward: Access logs If you configure CloudFront to log requests and to log cookies, CloudFront logs all cookies and all cookie attributes, even if you configure CloudFront not to forward cookies to your origin or if you configure CloudFront to forward only specific cookies. For more information about CloudFront logging, see Standard logging (access logs). Case sensitivity Cookie names and values are both case-sensitive. For example, if CloudFront is configured to forward all cookies, and two viewer requests for the same object have cookies that are identical except for case, CloudFront caches the object twice. CloudFront sorts cookies If CloudFront is configured to forward cookies (all or a subset), CloudFront sorts the cookies in natural order by cookie name before forwarding the request to your origin. Note Cookie names that start with the $ character are unsupported. CloudFront will remove the cookie before forwarding the request to the origin. You can remove the $ character or specify a different character at the start of the cookie name. If-Modified-Since and If-None-Match If-Modified-Since and If-None-Match conditional requests are not supported when CloudFront is configured to forward cookies (all or a subset). Cache content based on cookies 205 Amazon CloudFront Developer Guide Standard name–value pair format is required CloudFront forwards a cookie header only if the value conforms to the standard name–value pair format, for example: "Cookie: cookie1=value1; cookie2=value2" Disable caching of Set-Cookie headers If CloudFront is configured to forward cookies to the origin (whether all or specific cookies), it also caches the Set-Cookie headers received in the origin response. CloudFront includes these Set-Cookie headers in its response to the original viewer, and also includes them in subsequent responses that are served from the CloudFront cache. If you want to receive cookies at your origin but you don’t want CloudFront to cache the Set- Cookie headers in your origin’s responses, configure your origin to add a Cache-Control header with a no-cache directive that specifies Set-Cookie as a field name. For example: Cache-Control: no-cache="Set-Cookie". For more information, see Response Cache- Control Directives in the Hypertext Transfer Protocol (HTTP/1.1): Caching standard. Maximum length of cookie names If you configure CloudFront to forward specific cookies to your origin, the total number of bytes in all of the cookie names that you configure CloudFront to forward can’t exceed 512 minus the number of cookies that you’re forwarding. For example, if you configure CloudFront to forward 10 cookies to your origin, the combined length of the names of the 10 cookies can’t exceed 502 bytes (512 – 10). If you configure CloudFront to forward all cookies to your origin, the length of cookie names doesn’t matter. For information about using the CloudFront console to update a distribution so CloudFront forwards cookies to the origin, see Update a distribution. For information about using the CloudFront API to update a distribution, see UpdateDistribution in the Amazon CloudFront API Reference. Cache |
AmazonCloudFront_DevGuide-083 | AmazonCloudFront_DevGuide.pdf | 83 | exceed 512 minus the number of cookies that you’re forwarding. For example, if you configure CloudFront to forward 10 cookies to your origin, the combined length of the names of the 10 cookies can’t exceed 502 bytes (512 – 10). If you configure CloudFront to forward all cookies to your origin, the length of cookie names doesn’t matter. For information about using the CloudFront console to update a distribution so CloudFront forwards cookies to the origin, see Update a distribution. For information about using the CloudFront API to update a distribution, see UpdateDistribution in the Amazon CloudFront API Reference. Cache content based on request headers CloudFront lets you choose whether you want CloudFront to forward headers to your origin and to cache separate versions of a specified object based on the header values in viewer requests. This allows you to serve different versions of your content based on the device the user is using, the location of the viewer, the language the viewer is using, and a variety of other criteria. Cache content based on request headers 206 Developer Guide Amazon CloudFront Topics • Headers and distributions – overview • Select the headers to base caching on • Configure CloudFront to respect CORS settings • Configure caching based on the device type • Configure caching based on the language of the viewer • Configure caching based on the location of the viewer • Configure caching based on the protocol of the request • Configure caching for compressed files • How caching based on headers affects performance • How the case of headers and header values affects caching • Headers that CloudFront returns to the viewer Headers and distributions – overview By default, CloudFront doesn't consider headers when caching your objects in edge locations. If your origin returns two objects and they differ only by the values in the request headers, CloudFront caches only one version of the object. You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers. For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex. You can configure each cache behavior in a distribution to do one of the following: • Forward all headers to your origin Headers and distributions – overview 207 Amazon CloudFront Note Developer Guide For legacy cache settings – If you configure CloudFront to forward all headers to your origin, CloudFront doesn't cache the objects associated with this cache behavior. Instead, it sends every request to the origin. • Forward a list of headers that you specify. CloudFront caches your objects based on the values in all of the specified headers. CloudFront also forwards the headers that it forwards by default, but it caches your objects based only on the headers that you specify. • Forward only the default headers. In this configuration, CloudFront doesn't cache your objects based on the values in the request headers. For the current quota on the number of headers that you can forward for each cache behavior or to request a higher quota, see Quotas on headers. For information about using the CloudFront console to update a distribution so CloudFront forwards headers to the origin, see Update a distribution. For information about using the CloudFront API to update an existing distribution, see Update Distribution in the Amazon CloudFront API Reference. Select the headers to base caching on The headers that you can forward to the origin and that CloudFront bases caching on depend on whether your origin is an Amazon S3 bucket or a custom origin. • Amazon S3 – You can configure CloudFront to forward and to cache your objects based on a number of specific headers (see the following list of exceptions). However, we recommend that you avoid forwarding headers with an Amazon S3 origin unless you need to implement cross- origin resource sharing (CORS) or you want to personalize content by using Lambda@Edge in origin-facing events. • To configure CORS, you must forward headers that allow CloudFront to distribute content for websites that are enabled for cross-origin resource sharing (CORS). For more information, see Configure CloudFront to respect CORS settings. • To personalize content |
AmazonCloudFront_DevGuide-084 | AmazonCloudFront_DevGuide.pdf | 84 | Amazon S3 – You can configure CloudFront to forward and to cache your objects based on a number of specific headers (see the following list of exceptions). However, we recommend that you avoid forwarding headers with an Amazon S3 origin unless you need to implement cross- origin resource sharing (CORS) or you want to personalize content by using Lambda@Edge in origin-facing events. • To configure CORS, you must forward headers that allow CloudFront to distribute content for websites that are enabled for cross-origin resource sharing (CORS). For more information, see Configure CloudFront to respect CORS settings. • To personalize content by using headers that you forward to your Amazon S3 origin, you write and add Lambda@Edge functions and associate them with your CloudFront distribution to Select the headers to base caching on 208 Amazon CloudFront Developer Guide be triggered by an origin-facing event. For more information about working with headers to personalize content, see Personalize content by country or device type headers - examples. We recommend that you avoid forwarding headers that you aren’t using to personalize content because forwarding extra headers can reduce your cache hit ratio. That is, CloudFront can’t serve as many requests from edge caches, as a proportion of all requests. • Custom origin – You can configure CloudFront to cache based on the value of any request header except the following: • Connection • Cookie – If you want to forward and cache based on cookies, you use a separate setting in your distribution. For more information, see Cache content based on cookies. • Host (for Amazon S3 origins) • Proxy-Authorization • TE • Upgrade You can configure CloudFront to cache objects based on values in the Date and User-Agent headers, but we don’t recommend it. These headers have numerous possible values, and caching based on their values could cause CloudFront to forward significantly more requests to your origin. For a full list of HTTP request headers and how CloudFront processes them, see HTTP request headers and CloudFront behavior (custom and Amazon S3 origins). Configure CloudFront to respect CORS settings If you have enabled cross-origin resource sharing (CORS) on an Amazon S3 bucket or a custom origin, you must choose specific headers to forward, to respect the CORS settings. The headers that you must forward differ depending on the origin (Amazon S3 or custom) and whether you want to cache OPTIONS responses. Amazon S3 • If you want OPTIONS responses to be cached, do the following: • Choose the options for default cache behavior settings that enable caching for OPTIONS responses. Configure CloudFront to respect CORS settings 209 Amazon CloudFront Developer Guide • Configure CloudFront to forward the following headers: Origin, Access-Control- Request-Headers, and Access-Control-Request-Method. • If you don't want OPTIONS responses to be cached, configure CloudFront to forward the Origin header, together with any other headers required by your origin (for example, Access- Control-Request-Headers, Access-Control-Request-Method, or others). Custom origins – Forward the Origin header along with any other headers required by your origin. To configure CloudFront to cache responses based on CORS, you must configure CloudFront to forward headers by using a cache policy. For more information, see Control the cache key with a policy. For more information about CORS and Amazon S3, see Using cross-origin resource sharing (CORS) in the Amazon Simple Storage Service User Guide. Configure caching based on the device type If you want CloudFront to cache different versions of your objects based on the device a user is using to view your content, configure CloudFront to forward the applicable headers to your custom origin: • CloudFront-Is-Desktop-Viewer • CloudFront-Is-Mobile-Viewer • CloudFront-Is-SmartTV-Viewer • CloudFront-Is-Tablet-Viewer Based on the value of the User-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. For example, for some tablet devices, CloudFront might set both CloudFront-Is-Mobile-Viewer and CloudFront-Is-Tablet-Viewer to true. Configure caching based on the language of the viewer If you want CloudFront to cache different versions of your objects based on the language specified in the request, configure CloudFront to forward the Accept-Language header to your origin. Configure caching based on the device type 210 Amazon CloudFront Developer Guide Configure caching based on the location of the viewer If you want CloudFront to cache different versions of your objects based on the country that the request came from, configure CloudFront to forward the CloudFront-Viewer-Country header to your origin. CloudFront automatically converts the IP address that the request came from into a two-letter country code. For an easy-to-use list of country codes, sortable by code and by country name, see the Wikipedia entry ISO 3166-1 alpha-2. Configure caching based on the protocol of the request If you want CloudFront to cache |
AmazonCloudFront_DevGuide-085 | AmazonCloudFront_DevGuide.pdf | 85 | on the device type 210 Amazon CloudFront Developer Guide Configure caching based on the location of the viewer If you want CloudFront to cache different versions of your objects based on the country that the request came from, configure CloudFront to forward the CloudFront-Viewer-Country header to your origin. CloudFront automatically converts the IP address that the request came from into a two-letter country code. For an easy-to-use list of country codes, sortable by code and by country name, see the Wikipedia entry ISO 3166-1 alpha-2. Configure caching based on the protocol of the request If you want CloudFront to cache different versions of your objects based on the protocol of the request, HTTP or HTTPS, configure CloudFront to forward the CloudFront-Forwarded-Proto header to your origin. Configure caching for compressed files If your origin supports Brotli compression, you can cache based on the Accept-Encoding header. Configure caching based on Accept-Encoding only if your origin serves different content based on the header. How caching based on headers affects performance When you configure CloudFront to cache based on one or more headers and the headers have more than one possible value, CloudFront forwards more requests to your origin server for the same object. This slows performance and increases the load on your origin server. If your origin server returns the same object regardless of the value of a given header, we recommend that you don't configure CloudFront to cache based on that header. If you configure CloudFront to forward more than one header, the order of the headers in viewer requests doesn't affect caching as long as the values are the same. For example, if one request contains the headers A:1,B:2 and another request contains B:2,A:1, CloudFront caches just one copy of the object. How the case of headers and header values affects caching When CloudFront caches based on header values, it doesn't consider the case of the header name, but it does consider the case of the header value: Configure caching based on the location of the viewer 211 Amazon CloudFront Developer Guide • If viewer requests include both Product:Acme and product:Acme, CloudFront caches an object only once. The only difference between them is the case of the header name, which doesn't affect caching. • If viewer requests include both Product:Acme and Product:acme, CloudFront caches an object twice, because the value is Acme in some requests and acme in others. Headers that CloudFront returns to the viewer Configuring CloudFront to forward and cache headers does not affect which headers CloudFront returns to the viewer. CloudFront returns all of the headers that it gets from the origin with a few exceptions. For more information, see the applicable topic: • Amazon S3 origins – See HTTP response headers that CloudFront removes or updates. • Custom origins – See HTTP response headers that CloudFront removes or replaces. Headers that CloudFront returns to the viewer 212 Amazon CloudFront Developer Guide Control the cache key with a policy With a CloudFront cache policy, you can specify the HTTP headers, cookies, and query strings that CloudFront includes in the cache key for objects that are cached at CloudFront edge locations. The cache key is the unique identifier for every object in the cache, and it determines whether a viewer's HTTP request results in a cache hit. A cache hit occurs when a viewer request generates the same cache key as a prior request, and the object for that cache key is in the edge location's cache and valid. When there's a cache hit, the object is served to the viewer from a CloudFront edge location, which has the following benefits: • Reduced load on your origin server • Reduced latency for the viewer Including fewer values in the cache key increases the likelihood of a cache hit. This can get you better performance from your website or application because there's a higher cache hit ratio (a higher proportion of viewer requests that result in a cache hit). For more information, see Understand the cache key. To control the cache key, you use a CloudFront cache policy. You attach a cache policy to one or more cache behaviors in a CloudFront distribution. You can also use the cache policy to specify time to live (TTL) settings for objects in the CloudFront cache, and enable CloudFront to request and cache compressed objects. Note Cache settings don't affect gRPC requests because gRPC traffic can't be cached. For more information, see Using gRPC with CloudFront distributions. Topics • Understand cache policies • Create cache policies • Use managed cache policies • Understand the cache key 213 Amazon CloudFront Developer Guide Understand cache policies You can use a cache policy to improve your cache hit ratio by controlling the values (URL query strings, HTTP headers, and cookies) that are included in the cache |
AmazonCloudFront_DevGuide-086 | AmazonCloudFront_DevGuide.pdf | 86 | to specify time to live (TTL) settings for objects in the CloudFront cache, and enable CloudFront to request and cache compressed objects. Note Cache settings don't affect gRPC requests because gRPC traffic can't be cached. For more information, see Using gRPC with CloudFront distributions. Topics • Understand cache policies • Create cache policies • Use managed cache policies • Understand the cache key 213 Amazon CloudFront Developer Guide Understand cache policies You can use a cache policy to improve your cache hit ratio by controlling the values (URL query strings, HTTP headers, and cookies) that are included in the cache key. CloudFront provides some predefined cache policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own cache policy that's specific to your needs. For more information about the managed policies, see Use managed cache policies. A cache policy contains the following settings, which are categorized into policy information, time to live (TTL) settings, and cache key settings. Policy information Name A name to identify the cache policy. In the console, you use the name to attach the cache policy to a cache behavior. Description A comment to describe the cache policy. This is optional, but it can help you identify the purpose of the cache policy. Time to live (TTL) settings The time to live (TTL) settings work together with the Cache-Control and Expires HTTP headers (if they're in the origin response) to determine how long objects in the CloudFront cache remain valid. Minimum TTL The minimum amount of time, in seconds, that you want objects to stay in the CloudFront cache before CloudFront checks with the origin to see if the object has been updated. For more information, see Manage how long content stays in the cache (expiration). Maximum TTL The maximum amount of time, in seconds, that objects stay in the CloudFront cache before CloudFront checks with the origin to see if the object has been updated. CloudFront uses this setting only when the origin sends Cache-Control or Expires headers with the object. For more information, see Manage how long content stays in the cache (expiration). Understand cache policies 214 Amazon CloudFront Default TTL Developer Guide The default amount of time, in seconds, that you want objects to stay in the CloudFront cache before CloudFront checks with the origin to see if the object has been updated. CloudFront uses this setting's value as the object's TTL only when the origin does not send Cache-Control or Expires headers with the object. For more information, see Manage how long content stays in the cache (expiration). Note If the Minimum TTL, Maximum TTL, and Default TTL settings are all set to 0, this disables CloudFront caching. Cache key settings Cache key settings specify the values in viewer requests that CloudFront includes in the cache key. The values can include URL query strings, HTTP headers, and cookies. The values that you include in the cache key are automatically included in requests that CloudFront sends to the origin, known as origin requests. For information about controlling origin requests without affecting the cache key, see Control origin requests with a policy. Cache key settings include: • Headers • Cookies • Query strings • Compression support Headers The HTTP headers in viewer requests that CloudFront includes in the cache key and in origin requests. For headers, you can choose one of the following settings: • None – The HTTP headers in viewer requests are not included in the cache key and are not automatically included in origin requests. • Include the following headers – You specify which of the HTTP headers in viewer requests are included in the cache key and automatically included in origin requests. Cache key settings 215 Amazon CloudFront Developer Guide When you use the Include the following headers setting, you specify HTTP headers by their name, not their value. For example, consider the following HTTP header: Accept-Language: en-US,en;q=0.5 In this case, you specify the header as Accept-Language, not as Accept-Language: en- US,en;q=0.5. However, CloudFront includes the full header, including its value, in the cache key and in origin requests. You can also include certain headers generated by CloudFront in the cache key. For more information, see the section called “Add CloudFront request headers”. Cookies The cookies in viewer requests that CloudFront includes in the cache key and in origin requests. For cookies, you can choose one of the following settings: • None – The cookies in viewer requests are not included in the cache key and are not automatically included in origin requests. • All – All cookies in viewer requests are included in the cache key and are automatically included in origin requests. • Include specified cookies – You specify which of the cookies in viewer requests are included |
AmazonCloudFront_DevGuide-087 | AmazonCloudFront_DevGuide.pdf | 87 | cache key. For more information, see the section called “Add CloudFront request headers”. Cookies The cookies in viewer requests that CloudFront includes in the cache key and in origin requests. For cookies, you can choose one of the following settings: • None – The cookies in viewer requests are not included in the cache key and are not automatically included in origin requests. • All – All cookies in viewer requests are included in the cache key and are automatically included in origin requests. • Include specified cookies – You specify which of the cookies in viewer requests are included in the cache key and automatically included in origin requests. • Include all cookies except – You specify which of the cookies in viewer requests are not included in the cache key and are not automatically included in origin requests. All other cookies, except for the ones you specify, are included in the cache key and automatically included in origin requests. When you use the Include specified cookies or Include all cookies except setting, you specify cookies by their name, not their value. For example, consider the following Cookie header: Cookie: session_ID=abcd1234 In this case, you specify the cookie as session_ID, not as session_ID=abcd1234. However, CloudFront includes the full cookie, including its value, in the cache key and in origin requests. Query strings The URL query strings in viewer requests that CloudFront includes in the cache key and in origin requests. For query strings, you can choose one of the following settings: Cache key settings 216 Amazon CloudFront Developer Guide • None – The query strings in viewer requests are not included in the cache key and are not automatically included in origin requests. • All – All query strings in viewer requests are included in the cache key and are also automatically included in origin requests. • Include specified query strings – You specify which of the query strings in viewer requests are included in the cache key and automatically included in origin requests. • Include all query strings except – You specify which of the query strings in viewer requests are not included in the cache key and are not automatically included in origin requests. All other query strings, except for the ones you specify, are included in the cache key and automatically included in origin requests. When you use the Include specified query strings or Include all query strings except setting, you specify query strings by their name, not their value. For example, consider the following URL path: /content/stories/example-story.html?split-pages=false In this case, you specify the query string as split-pages, not as split-pages=false. However, CloudFront includes the full query string, including its value, in the cache key and in origin requests. Note For the cache key settings, CloudFront treats the asterisk character (*) for the headers, query strings, and cookies as a literal string, not as a wildcard. Compression support These settings enable CloudFront to request and cache objects that are compressed in the Gzip or Brotli compression formats, when the viewer supports it. These settings also allow CloudFront compression to work. Viewers indicate their support for these compression formats with the Accept-Encoding HTTP header. Cache key settings 217 Amazon CloudFront Note Developer Guide The Chrome and Firefox web browsers support Brotli compression only when the request is sent using HTTPS. These browsers do not support Brotli with HTTP requests. Enable these settings when any of the following are true: • Your origin returns Gzip compressed objects when viewers support them (requests contain the Accept-Encoding HTTP header with gzip as a value). In this case, use the Gzip enabled setting (set EnableAcceptEncodingGzip to true in the CloudFront API, AWS SDKs, AWS CLI, or AWS CloudFormation). • Your origin returns Brotli compressed objects when viewers support them (requests contain the Accept-Encoding HTTP header with br as a value). In this case, use the Brotli enabled setting (set EnableAcceptEncodingBrotli to true in the CloudFront API, AWS SDKs, AWS CLI, or AWS CloudFormation). • The cache behavior that this cache policy is attached to is configured with CloudFront compression. In this case, you can enable caching for either Gzip or Brotli, or both. When CloudFront compression is enabled, enabling caching for both formats can help to reduce your costs for data transfer out to the internet. Note If you enable caching for one or both of these compression formats, do not include the Accept-Encoding header in an origin request policy that's associated with the same cache behavior. CloudFront always includes this header in origin requests when caching is enabled for either of these formats, so including Accept-Encoding in an origin request policy has no effect. If your origin server does not return Gzip or Brotli compressed objects, or the cache behavior is not configured with CloudFront compression, don't enable caching for |
AmazonCloudFront_DevGuide-088 | AmazonCloudFront_DevGuide.pdf | 88 | both formats can help to reduce your costs for data transfer out to the internet. Note If you enable caching for one or both of these compression formats, do not include the Accept-Encoding header in an origin request policy that's associated with the same cache behavior. CloudFront always includes this header in origin requests when caching is enabled for either of these formats, so including Accept-Encoding in an origin request policy has no effect. If your origin server does not return Gzip or Brotli compressed objects, or the cache behavior is not configured with CloudFront compression, don't enable caching for compressed objects. If you do, it might cause a decrease in your cache hit ratio. The following explains how these settings affect a CloudFront distribution. All of the following scenarios assume that the viewer request includes the Accept-Encoding header. When the viewer request does not include the Accept-Encoding header, CloudFront doesn't include this header in the cache key and doesn't include it in the corresponding origin request. Cache key settings 218 Amazon CloudFront Developer Guide When caching compressed objects is enabled for both compression formats If the viewer supports both Gzip and Brotli—that is, if the gzip and br values are both in the Accept-Encoding header in the viewer request—CloudFront does the following: • Normalizes the header to Accept-Encoding: br,gzip and includes the normalized header in the cache key. The cache key doesn't include other values that were in the Accept-Encoding header sent by the viewer. • If the edge location has a Brotli or Gzip compressed object in the cache that matches the request and is not expired, the edge location returns the object to the viewer. • If the edge location doesn't have a Brotli or Gzip compressed object in the cache that matches the request and is not expired, CloudFront includes the normalized header (Accept-Encoding: br,gzip) in the corresponding origin request. The origin request doesn't include other values that were in the Accept-Encoding header sent by the viewer. If the viewer supports one compression format but not the other—for example, if gzip is a value in the Accept-Encoding header in the viewer request but br is not—CloudFront does the following: • Normalizes the header to Accept-Encoding: gzip and includes the normalized header in the cache key. The cache key doesn't include other values that were in the Accept- Encoding header sent by the viewer. • If the edge location has a Gzip compressed object in the cache that matches the request and is not expired, the edge location returns the object to the viewer. • If the edge location doesn't have a Gzip compressed object in the cache that matches the request and is not expired, CloudFront includes the normalized header (Accept- Encoding: gzip) in the corresponding origin request. The origin request doesn't include other values that were in the Accept-Encoding header sent by the viewer. To understand what CloudFront does if the viewer supports Brotli but not Gzip, replace the two compression formats with each other in the preceding example. If the viewer does not support Brotli or Gzip—that is, the Accept-Encoding header in the viewer request does not contain br or gzip as values—CloudFront: • Doesn't include the Accept-Encoding header in the cache key. • Includes Accept-Encoding: identity in the corresponding origin request. The origin request doesn't include other values that were in the Accept-Encoding header sent by the viewer. Cache key settings 219 Amazon CloudFront Developer Guide When caching compressed objects is enabled for one compression format, but not the other If the viewer supports the format for which caching is enabled—for example, if caching compressed objects is enabled for Gzip and the viewer supports Gzip (gzip is one of the values in the Accept-Encoding header in the viewer request)—CloudFront does the following: • Normalizes the header to Accept-Encoding: gzip and includes the normalized header in the cache key. • If the edge location has a Gzip compressed object in the cache that matches the request and is not expired, the edge location returns the object to the viewer. • If the edge location doesn't have a Gzip compressed object in the cache that matches the request and is not expired, CloudFront includes the normalized header (Accept- Encoding: gzip) in the corresponding origin request. The origin request doesn't include other values that were in the Accept-Encoding header sent by the viewer. This behavior is the same when the viewer supports both Gzip and Brotli (the Accept- Encoding header in the viewer request includes both gzip and br as values), because in this scenario, caching compressed objects for Brotli is not enabled. To understand what CloudFront does if caching compressed objects is enabled for Brotli but not Gzip, replace the two compression formats with each other in the preceding example. If the viewer does not |
AmazonCloudFront_DevGuide-089 | AmazonCloudFront_DevGuide.pdf | 89 | normalized header (Accept- Encoding: gzip) in the corresponding origin request. The origin request doesn't include other values that were in the Accept-Encoding header sent by the viewer. This behavior is the same when the viewer supports both Gzip and Brotli (the Accept- Encoding header in the viewer request includes both gzip and br as values), because in this scenario, caching compressed objects for Brotli is not enabled. To understand what CloudFront does if caching compressed objects is enabled for Brotli but not Gzip, replace the two compression formats with each other in the preceding example. If the viewer does not support the compression format for which caching is enabled (the Accept-Encoding header in the viewer request doesn't contain the value for that format), CloudFront: • Doesn't include the Accept-Encoding header in the cache key. • Includes Accept-Encoding: identity in the corresponding origin request. The origin request doesn't include other values that were in the Accept-Encoding header sent by the viewer. When caching compressed objects is disabled for both compression formats When caching compressed objects is disabled for both compression formats, CloudFront treats the Accept-Encoding header the same as any other HTTP header in the viewer request. By default, it's not included in the cache key and it's not included in origin requests. You can include it in the headers list in a cache policy or an origin request policy the same as any other HTTP header. Cache key settings 220 Amazon CloudFront Developer Guide Create cache policies You can use a cache policy to improve your cache hit ratio by controlling the values (URL query strings, HTTP headers, and cookies) that are included in the cache key. You can create a cache policy in the CloudFront console, with the AWS Command Line Interface (AWS CLI), or with the CloudFront API. After you create a cache policy, you attach it to one or more cache behaviors in a CloudFront distribution. Console To create a cache policy (console) 1. Sign in to the AWS Management Console and open the Policies page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home?#/policies. 2. Choose Create cache policy. 3. Choose the desired setting for this cache policy. For more information, see Understand cache policies. 4. When finished, choose Create. After you create a cache policy, you can attach it to a cache behavior. To attach a cache policy to an existing distribution (console) 1. Open the Distributions page in the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home#/distributions. 2. Choose the distribution to update, then choose the Behaviors tab. 3. Choose the cache behavior to update, then choose Edit. Or, to create a new cache behavior, choose Create behavior. 4. In the Cache key and origin requests section, make sure that Cache policy and origin request policy is chosen. 5. For Cache policy, choose the cache policy to attach to this cache behavior. 6. At the bottom of the page, choose Save changes. Create cache policies 221 Amazon CloudFront Developer Guide To attach a cache policy to a new distribution (console) 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose Create distribution. 3. 4. In the Cache key and origin requests section, make sure that Cache policy and origin request policy is chosen. For Cache policy, choose the cache policy to attach to this distribution's default cache behavior. 5. Choose the desired settings for the origin, default cache behavior, and other distribution settings. For more information, see Distribution settings reference. 6. When finished, choose Create distribution. CLI To create a cache policy with the AWS Command Line Interface (AWS CLI), use the aws cloudfront create-cache-policy command. You can use an input file to provide the command's input parameters, rather than specifying each individual parameter as command line input. To create a cache policy (CLI with input file) 1. Use the following command to create a file named cache-policy.yaml that contains all of the input parameters for the create-cache-policy command. aws cloudfront create-cache-policy --generate-cli-skeleton yaml-input > cache- policy.yaml 2. Open the file named cache-policy.yaml that you just created. Edit the file to specify the cache policy settings that you want, then save the file. You can remove optional fields from the file, but don't remove the required fields. For more information about the cache policy settings, see Understand cache policies. 3. Use the following command to create the cache policy using input parameters from the cache-policy.yaml file. aws cloudfront create-cache-policy --cli-input-yaml file://cache-policy.yaml Create cache policies 222 Amazon CloudFront Developer Guide Make note of the Id value in the command's output. This is the cache policy ID, and you need it to attach the cache policy to a CloudFront distribution's cache behavior. To attach a cache policy to an existing distribution (CLI with input file) 1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to |
AmazonCloudFront_DevGuide-090 | AmazonCloudFront_DevGuide.pdf | 90 | the cache policy settings, see Understand cache policies. 3. Use the following command to create the cache policy using input parameters from the cache-policy.yaml file. aws cloudfront create-cache-policy --cli-input-yaml file://cache-policy.yaml Create cache policies 222 Amazon CloudFront Developer Guide Make note of the Id value in the command's output. This is the cache policy ID, and you need it to attach the cache policy to a CloudFront distribution's cache behavior. To attach a cache policy to an existing distribution (CLI with input file) 1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to update. Replace distribution_ID with the distribution's ID. aws cloudfront get-distribution-config --id distribution_ID --output yaml > dist-config.yaml 2. Open the file named dist-config.yaml that you just created. Edit the file, making the following changes to each cache behavior that you are updating to use a cache policy. • In the cache behavior, add a field named CachePolicyId. For the field's value, use the cache policy ID that you noted after creating the policy. • Remove the MinTTL, MaxTTL, DefaultTTL, and ForwardedValues fields from the cache behavior. These settings are specified in the cache policy, so you can't include these fields and a cache policy in the same cache behavior. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the distribution to use the cache policy. Replace distribution_ID with the distribution's ID. aws cloudfront update-distribution --id distribution_ID --cli-input-yaml file:// dist-config.yaml To attach a cache policy to a new distribution (CLI with input file) 1. Use the following command to create a file named distribution.yaml that contains all of the input parameters for the create-distribution command. Create cache policies 223 Amazon CloudFront Developer Guide aws cloudfront create-distribution --generate-cli-skeleton yaml-input > distribution.yaml 2. Open the file named distribution.yaml that you just created. In the default cache behavior, in the CachePolicyId field, enter the cache policy ID that you noted after creating the policy. Continue editing the file to specify the distribution settings that you want, then save the file when finished. For more information about the distribution settings, see Distribution settings reference. 3. Use the following command to create the distribution using input parameters from the distribution.yaml file. aws cloudfront create-distribution --cli-input-yaml file://distribution.yaml API To create a cache policy with the CloudFront API, use CreateCachePolicy. For more information about the fields that you specify in this API call, see Understand cache policies and the API reference documentation for your AWS SDK or other API client. After you create a cache policy, you can attach it to a cache behavior, using one of the following API calls: • To attach it to a cache behavior in an existing distribution, use UpdateDistribution. • To attach it to a cache behavior in a new distribution, use CreateDistribution. For both of these API calls, provide the cache policy's ID in the CachePolicyId field, inside a cache behavior. For more information about the other fields that you specify in these API calls, see Distribution settings reference and the API reference documentation for your AWS SDK or other API client. Use managed cache policies CloudFront provides a set of managed cache policies that you can attach to any of your distribution's cache behaviors. With a managed cache policy, you don't need to write or maintain your own cache policy. The managed policies use settings that are optimized for specific use cases. Use managed cache policies 224 Amazon CloudFront Developer Guide To use a managed cache policy, you attach it to a cache behavior in your distribution. The process is the same as when you create a cache policy, but instead of creating a new one, you just attach one of the managed cache policies. You attach the policy either by name (with the console) or by ID (with the AWS CLI or SDKs). The names and IDs are listed in the following section. For more information, see Create cache policies. The following topics describe the managed cache policies that you can use. Topics • Amplify • CachingDisabled • CachingOptimized • CachingOptimizedForUncompressedObjects • Elemental-MediaPackage • UseOriginCacheControlHeaders • UseOriginCacheControlHeaders-QueryStrings Amplify View this policy in the CloudFront console This policy is designed for use with an origin that is an AWS Amplify web app. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 2e54312d-136d-493c-8eb9-b001f22f67d2 This policy has the following settings: • Minimum TTL: 2 seconds • Maximum TTL: 600 seconds (10 minutes) • Default TTL: 2 seconds • Headers included in cache key: • Authorization • CloudFront-Viewer-Country Amplify 225 Amazon CloudFront • Host Developer Guide The normalized Accept-Encoding header is also included because the cache compressed objects setting is enabled. For more information, see Compression support. • Cookies included |
AmazonCloudFront_DevGuide-091 | AmazonCloudFront_DevGuide.pdf | 91 | console This policy is designed for use with an origin that is an AWS Amplify web app. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 2e54312d-136d-493c-8eb9-b001f22f67d2 This policy has the following settings: • Minimum TTL: 2 seconds • Maximum TTL: 600 seconds (10 minutes) • Default TTL: 2 seconds • Headers included in cache key: • Authorization • CloudFront-Viewer-Country Amplify 225 Amazon CloudFront • Host Developer Guide The normalized Accept-Encoding header is also included because the cache compressed objects setting is enabled. For more information, see Compression support. • Cookies included in cache key: All cookies are included. • Query strings included in cache key: All query strings are included. • Cache compressed objects setting: Enabled. For more information, see Compression support. AWS Amplify Hosting cache policies Amplify uses the following managed cache policies to optimize the default cache configuration for customers' applications: • Amplify-Default • Amplify-DefaultNoCookies • Amplify-ImageOptimization • Amplify-StaticContent Note These policies are only used by Amplify. We don't recommend that you use these policies for your distributions. For more information about managing cache configuration for your Amplify hosted application, see Managing cache configuration in the Amplify Hosting User Guide. CachingDisabled View this policy in the CloudFront console This policy disables caching. This policy is useful for dynamic content and for requests that are not cacheable. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad CachingDisabled 226 Amazon CloudFront Developer Guide This policy has the following settings: • Minimum TTL: 0 seconds • Maximum TTL: 0 seconds • Default TTL: 0 seconds • Headers included in the cache key: None • Cookies included in the cache key: None • Query strings included in the cache key: None • Cache compressed objects setting: Disabled CachingOptimized View this policy in the CloudFront console This policy is designed to optimize cache efficiency by minimizing the values that CloudFront includes in the cache key. CloudFront doesn't include any query strings or cookies in the cache key, and only includes the normalized Accept-Encoding header. This enables CloudFront to separately cache objects in the Gzip and Brotli compressions formats when the origin returns them or when CloudFront edge compression is enabled. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 658327ea-f89d-4fab-a63d-7e88639e58f6 This policy has the following settings: • Minimum TTL: 1 second. • Maximum TTL: 31,536,000 seconds (365 days). • Default TTL: 86,400 seconds (24 hours). • Headers included in the cache key: None are explicitly included. The normalized Accept- Encoding header is included because the cache compressed objects setting is enabled. For more information, see Compression support. • Cookies included in the cache key: None. • Query strings included in the cache key: None. • Cache compressed objects setting: Enabled. For more information, see Compression support. CachingOptimized 227 Amazon CloudFront Developer Guide CachingOptimizedForUncompressedObjects View this policy in the CloudFront console This policy is designed to optimize cache efficiency by minimizing the values included in the cache key. No query strings, headers, or cookies are included. This policy is identical to the previous one, but it disables the cache compressed objects setting. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: b2884449-e4de-46a7-ac36-70bc7f1ddd6d This policy has the following settings: • Minimum TTL: 1 second • Maximum TTL: 31,536,000 seconds (365 days) • Default TTL: 86,400 seconds (24 hours) • Headers included in the cache key: None • Cookies included in the cache key: None • Query strings included in the cache key: None • Cache compressed objects setting: Disabled Elemental-MediaPackage View this policy in the CloudFront console This policy is designed for use with an origin that is an AWS Elemental MediaPackage endpoint. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 08627262-05a9-4f76-9ded-b50ca2e3a84f This policy has the following settings: • Minimum TTL: 0 seconds • Maximum TTL: 31,536,000 seconds (365 days) • Default TTL: 86,400 seconds (24 hours) • Headers included in the cache key: • Origin CachingOptimizedForUncompressedObjects 228 Amazon CloudFront Developer Guide The normalized Accept-Encoding header is also included because the cache compressed objects setting is enabled for Gzip. For more information, see Compression support. • Cookies included in the cache key: None • Query strings included in the cache key: • aws.manifestfilter • start • end • m • Cache compressed objects setting: Enabled for Gzip. For more information, see Compression support. UseOriginCacheControlHeaders View this policy in the CloudFront console This policy is designed for use with an origin that returns Cache-Control HTTP response headers and does not serve different content based on values present in the query string. If your origin serves different content based on values present in the |
AmazonCloudFront_DevGuide-092 | AmazonCloudFront_DevGuide.pdf | 92 | compressed objects setting is enabled for Gzip. For more information, see Compression support. • Cookies included in the cache key: None • Query strings included in the cache key: • aws.manifestfilter • start • end • m • Cache compressed objects setting: Enabled for Gzip. For more information, see Compression support. UseOriginCacheControlHeaders View this policy in the CloudFront console This policy is designed for use with an origin that returns Cache-Control HTTP response headers and does not serve different content based on values present in the query string. If your origin serves different content based on values present in the query string, consider using UseOriginCacheControlHeaders-QueryStrings. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 83da9c7e-98b4-4e11-a168-04f0df8e2c65 This policy has the following settings: • Minimum TTL: 0 seconds • Maximum TTL: 31,536,000 seconds (365 days) • Default TTL: 0 seconds • Headers included in the cache key: • Host • Origin • X-HTTP-Method-Override • X-HTTP-Method • X-Method-Override UseOriginCacheControlHeaders 229 Amazon CloudFront Developer Guide The normalized Accept-Encoding header is also included because the cache compressed objects setting is enabled. For more information, see Compression support. • Cookies included in the cache key: All cookies are included. • Query strings included in the cache key: None. • Cache compressed objects setting: Enabled. For more information, see Compression support. UseOriginCacheControlHeaders-QueryStrings View this policy in the CloudFront console This policy is designed for use with an origin that returns Cache-Control HTTP response headers and serves different content based on values present in the query string. If your origin does not serve different content based on values present in the query string, consider using UseOriginCacheControlHeaders. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 4cc15a8a-d715-48a4-82b8-cc0b614638fe This policy has the following settings: • Minimum TTL: 0 seconds • Maximum TTL: 31,536,000 seconds (365 days) • Default TTL: 0 seconds • Headers included in the cache key: • Host • Origin • X-HTTP-Method-Override • X-HTTP-Method • X-Method-Override The normalized Accept-Encoding header is also included because the cache compressed objects setting is enabled. For more information, see Compression support. • Cookies included in the cache key: All cookies are included. • Query strings included in the cache key: All query strings are included. UseOriginCacheControlHeaders-QueryStrings 230 Amazon CloudFront Developer Guide • Cache compressed objects setting: Enabled. For more information, see Compression support. Understand the cache key The cache key determines whether a viewer request to a CloudFront edge location results in a cache hit. The cache key is the unique identifier for an object in the cache. Each object in the cache has a unique cache key. A cache hit occurs when a viewer request generates the same cache key as a prior request, and the object for that cache key is in the edge location’s cache and valid. When there’s a cache hit, the requested object is served to the viewer from a CloudFront edge location, which has the following benefits: • Reduced load on your origin server • Reduced latency for the viewer You can get better performance from your website or application when you have a higher cache hit ratio (a higher proportion of viewer requests that result in a cache hit). One way to improve your cache hit ratio is to include only the minimum necessary values in the cache key. For more information, see the following sections. You can modify the values (URL query strings, HTTP headers, and cookies) in the cache key by using a cache policy. (You can also modify the cache key by using a Lambda@Edgefunction or a CloudFront Function on a viewer request.) Before modifying the cache key, it’s important to understand how your application is designed and when and how it might serve different responses based on characteristics of the viewer request. When a value in the viewer request determines the response that your origin returns, you should include that value in the cache key. But if you include a value in the cache key that doesn’t affect the response that your origin returns, you might end up caching duplicate objects. Default cache key By default, the cache key for a CloudFront distribution includes the following information: • The domain name of the CloudFront distribution (for example, d111111abcdef8.cloudfront.net) • The URL path of the requested object (for example, /content/stories/example- story.html) Understand the cache key 231 Amazon CloudFront Note Developer Guide The OPTIONS method is included in the cache key for OPTIONS requests. This means that responses to OPTIONS requests are cached separately from responses to GET and HEAD requests. Other values from the viewer request are not included in the cache key, by default. Consider the following HTTP request from a web browser. GET /content/stories/example-story.html?ref=0123abc&split-pages=false HTTP/1.1 Host: d111111abcdef8.cloudfront.net User-Agent: Mozilla/5.0 Gecko/20100101 Firefox/68.0 Accept: text/html,*/* Accept-Language: |
AmazonCloudFront_DevGuide-093 | AmazonCloudFront_DevGuide.pdf | 93 | following information: • The domain name of the CloudFront distribution (for example, d111111abcdef8.cloudfront.net) • The URL path of the requested object (for example, /content/stories/example- story.html) Understand the cache key 231 Amazon CloudFront Note Developer Guide The OPTIONS method is included in the cache key for OPTIONS requests. This means that responses to OPTIONS requests are cached separately from responses to GET and HEAD requests. Other values from the viewer request are not included in the cache key, by default. Consider the following HTTP request from a web browser. GET /content/stories/example-story.html?ref=0123abc&split-pages=false HTTP/1.1 Host: d111111abcdef8.cloudfront.net User-Agent: Mozilla/5.0 Gecko/20100101 Firefox/68.0 Accept: text/html,*/* Accept-Language: en-US,en Cookie: session_id=01234abcd Referer: https://news.example.com/ When a viewer request like this example comes in to a CloudFront edge location, CloudFront uses the cache key to determine if there’s a cache hit. By default, only the following components of the request are included in the cache key: /content/stories/example-story.html and d111111abcdef8.cloudfront.net. If the requested object is not in the cache (a cache miss), then CloudFront sends a request to the origin to get the object. After getting the object, CloudFront returns it to the viewer and stores it in the edge location’s cache. When CloudFront receives another request for the same object, as determined by the cache key, CloudFront serves the cached object to the viewer immediately, without sending a request to the origin. For example, consider the following HTTP request that comes in after the previous request. GET /content/stories/example-story.html?ref=xyz987&split-pages=true HTTP/1.1 Host: d111111abcdef8.cloudfront.net User-Agent: Mozilla/5.0 AppleWebKit/537.36 Chrome/83.0.4103.116 Accept: text/html,*/* Accept-Language: en-US,en Cookie: session_id=wxyz9876 Default cache key 232 Amazon CloudFront Developer Guide Referer: https://rss.news.example.net/ This request is for the same object as the previous request, but is different from the previous request. It has a different URL query string, different User-Agent and Referer headers, and a different session_id cookie. However, none of these values are part of the cache key by default, so this second request results in a cache hit. Customize the cache key In some cases, you might want to include more information in the cache key, even though doing so might result in fewer cache hits. You specify what to include in the cache key by using a cache policy. For example, if your origin server uses the Accept-Language HTTP header in viewer requests to return different content based on the viewer’s language, you might want to include this header in the cache key. When you do that, CloudFront uses this header to determine cache hits, and includes the header in origin requests (requests that CloudFront sends to the origin when there’s a cache miss). One potential consequence of including additional values in the cache key is that CloudFront might end up caching duplicate objects because of the variation that can occur in viewer requests. For example, viewers might send any of the following values for the Accept-Language header: • en-US,en • en,en-US • en-US, en • en-US All of these different values indicate that the viewer’s language is English, but the variation can cause CloudFront to cache the same object multiple times. This can reduce cache hits and increase the number of origin requests. You could avoid this duplication by not including the Accept- Language header in the cache key, and instead configuring your website or application to use different URLs for content in different languages (for example, /en-US/content/stories/ example-story.html). For any given value that you intend to include in the cache key, you should make sure that you understand how many different variations of that value might appear in viewer requests. For Customize the cache key 233 Amazon CloudFront Developer Guide certain request values, it rarely makes sense to include them in the cache key. For example, the User-Agent header can have thousands of unique variations, so it’s generally not a good candidate for including in the cache key. Cookies that have user-specific or session-specific values and are unique across thousands (or even millions) of requests are also not good candidates for cache key inclusion. If you do include these values in the cache key, each unique variation results in another copy of the object in the cache. If these copies of the object are not unique, or if you end up with such a large number of slightly different objects that each object only gets a small number of cache hits, you might want to consider a different approach. You can exclude these highly variable values from the cache key, or you can mark objects as non-cacheable. Use caution when customizing the cache key. Sometimes it’s desirable, but it can have unintended consequences such as caching duplicate objects, lowering your cache hit ratio, and increasing the number of origin requests. If your origin website or application needs to receive certain values from viewer requests for analytics, telemetry, or other uses, but these values don’t change the object |
AmazonCloudFront_DevGuide-094 | AmazonCloudFront_DevGuide.pdf | 94 | slightly different objects that each object only gets a small number of cache hits, you might want to consider a different approach. You can exclude these highly variable values from the cache key, or you can mark objects as non-cacheable. Use caution when customizing the cache key. Sometimes it’s desirable, but it can have unintended consequences such as caching duplicate objects, lowering your cache hit ratio, and increasing the number of origin requests. If your origin website or application needs to receive certain values from viewer requests for analytics, telemetry, or other uses, but these values don’t change the object that the origin returns, use an origin request policy to include these values in origin requests but not include them in the cache key. Customize the cache key 234 Amazon CloudFront Developer Guide Control origin requests with a policy When a viewer request to CloudFront results in a cache miss (the requested object is not cached at the edge location), CloudFront sends a request to the origin to retrieve the object. This is called an origin request. The origin request always includes the following information from the viewer request: • The URL path (the path only, without URL query strings or the domain name) • The request body (if there is one) • The HTTP headers that CloudFront automatically includes in every origin request, including Host, User-Agent, and X-Amz-Cf-Id Other information from the viewer request, such as URL query strings, HTTP headers, and cookies, is not included in the origin request by default. (Exception: With legacy cache settings, CloudFront forwards the headers to your origin by default.) However, you might want to receive some of this other information at the origin, for example to collect data for analytics or telemetry. You can use an origin request policy to control the information that's included in an origin request. Origin request policies are separate from cache policies, which control the cache key. This way, you can receive additional information at the origin and also maintain a good cache hit ratio (the proportion of viewer requests that result in a cache hit). You do this by separately controlling which information is included in origin requests (using the origin request policy) and which is included in the cache key (using the cache policy). Although the two kinds of policies are separate, they are related. All URL query strings, HTTP headers, and cookies that you include in the cache key (using a cache policy) are automatically included in origin requests. Use the origin request policy to specify the information that you want to include in origin requests, but not include in the cache key. Just like a cache policy, you attach an origin request policy to one or more cache behaviors in a CloudFront distribution. You can also use an origin request policy to add additional HTTP headers to an origin request that were not included in the viewer request. These additional headers are added by CloudFront before sending the origin request, with header values that are determined automatically based on the viewer request. For more information, see the section called “Add CloudFront request headers”. Topics • Understand origin request policies 235 Amazon CloudFront Developer Guide • Create origin request policies • Use managed origin request policies • Add CloudFront request headers • Understand how origin request policies and cache policies work together Understand origin request policies CloudFront provides some predefined origin request policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own origin request policy that's specific to your needs. For more information about the managed policies, see Use managed origin request policies. An origin request policy contains the following settings, which are categorized into policy information and origin request settings. Policy information Name A name to identify the origin request policy. In the console, you use the name to attach the origin request policy to a cache behavior. Description A comment to describe the origin request policy. This is optional. Origin request settings Origin request settings specify the values in viewer requests that are included in requests that CloudFront sends to the origin (known as origin requests). The values can include URL query strings, HTTP headers, and cookies. The values that you specify are included in origin requests, but are not included in the cache key. For information about controlling the cache key, see Control the cache key with a policy. Headers The HTTP headers in viewer requests that CloudFront includes in origin requests. For headers, you can choose one of the following settings: • None – The HTTP headers in viewer requests are not included in origin requests. Understand origin request policies 236 Amazon CloudFront Developer Guide • All viewer headers – All HTTP headers in viewer requests are included in |
AmazonCloudFront_DevGuide-095 | AmazonCloudFront_DevGuide.pdf | 95 | query strings, HTTP headers, and cookies. The values that you specify are included in origin requests, but are not included in the cache key. For information about controlling the cache key, see Control the cache key with a policy. Headers The HTTP headers in viewer requests that CloudFront includes in origin requests. For headers, you can choose one of the following settings: • None – The HTTP headers in viewer requests are not included in origin requests. Understand origin request policies 236 Amazon CloudFront Developer Guide • All viewer headers – All HTTP headers in viewer requests are included in origin requests. • All viewer headers and the following CloudFront headers – All HTTP headers in viewer requests are included in origin requests. Additionally, you specify which of the CloudFront headers you want to add to origin requests. For more information about the CloudFront headers, see the section called “Add CloudFront request headers”. • Include the following headers – You specify which HTTP headers are included in origin requests. Note Do not specify a header that is already included in your Origin Custom Headers settings. For more information, see Configure CloudFront to add custom headers to origin requests. • All viewer headers except – You specify which HTTP headers are not included in origin requests. All other HTTP headers in viewer requests, except for the ones specified, are included. When you use the All viewer headers and the following CloudFront headers, Include the following headers, or All viewer headers except setting, you specify HTTP headers by the header name only. CloudFront includes the full header, including its value, in origin requests. Note When you use the All viewer headers except setting to remove the viewer's Host header, CloudFront adds a new Host header with the origin's domain name to the origin request. Cookies The cookies in viewer requests that CloudFront includes in origin requests. For cookies, you can choose one of the following settings: • None – The cookies in viewer requests are not included in origin requests. • All – All cookies in viewer requests are included in origin requests. • Include the following cookies – You specify which cookies in viewer requests are included in origin requests. Origin request settings 237 Amazon CloudFront Developer Guide • All cookies except – You specify which cookies in viewer requests are not included in origin requests. All other cookies in viewer requests are included. When you use the Include the following cookies or All cookies except setting, you specify cookies by their name only. CloudFront includes the full cookie, including its value, in origin requests. Query strings The URL query strings in viewer requests that CloudFront includes in origin requests. For query strings, you can choose one of the following settings: • None – The query strings in viewer requests are not included in origin requests. • All – All query strings in viewer requests are included in origin requests. • Include the following query strings – You specify which query strings in viewer requests are included in origin requests. • All query strings except – You specify which query strings in viewer requests are not included in origin requests. All other query strings are included. When you use the Include the following query strings or All query strings except setting, you specify query strings by their name only. CloudFront includes the full query string, including its value, in origin requests. Create origin request policies You can use an origin request policy to control the values (URL query strings, HTTP headers, and cookies) that are included in requests that CloudFront sends to your origin. You can create an origin request policy in the CloudFront console, with the AWS Command Line Interface (AWS CLI), or with the CloudFront API. After you create an origin request policy, you attach it to one or more cache behaviors in a CloudFront distribution. Origin request policies are not required. When a cache behavior does not have an origin request policy attached, the origin request includes all the values that are specified in the cache policy, but nothing more. Create origin request policies 238 Amazon CloudFront Note Developer Guide To use an origin request policy, the cache behavior must also use a cache policy. You cannot use an origin request policy in a cache behavior without a cache policy. Console To create an origin request policy (console) 1. Sign in to the AWS Management Console and open the Policies page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home?#/policies. 2. Choose Origin request, then choose Create origin request policy. 3. Choose the desired setting for this origin request policy. For more information, see Understand origin request policies. 4. When finished, choose Create. After you create an origin request policy, you can attach it to a cache behavior. To attach an |
AmazonCloudFront_DevGuide-096 | AmazonCloudFront_DevGuide.pdf | 96 | behavior must also use a cache policy. You cannot use an origin request policy in a cache behavior without a cache policy. Console To create an origin request policy (console) 1. Sign in to the AWS Management Console and open the Policies page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home?#/policies. 2. Choose Origin request, then choose Create origin request policy. 3. Choose the desired setting for this origin request policy. For more information, see Understand origin request policies. 4. When finished, choose Create. After you create an origin request policy, you can attach it to a cache behavior. To attach an origin request policy to an existing distribution (console) 1. Open the Distributions page in the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home#/distributions. 2. Choose the distribution to update, then choose the Behaviors tab. 3. Choose the cache behavior to update, then choose Edit. Or, to create a new cache behavior, choose Create behavior. 4. In the Cache key and origin requests section, make sure that Cache policy and origin request policy is chosen. 5. For Origin request policy, choose the origin request policy to attach to this cache behavior. 6. At the bottom of the page, choose Save changes. To attach an origin request policy to a new distribution (console) 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose Create distribution. Create origin request policies 239 Amazon CloudFront Developer Guide 3. 4. In the Cache key and origin requests section, make sure that Cache policy and origin request policy is chosen. For Origin request policy, choose the origin request policy to attach to this distribution's default cache behavior. 5. Choose the desired settings for the origin, default cache behavior, and other distribution settings. For more information, see Distribution settings reference. 6. When finished, choose Create distribution. CLI To create an origin request policy with the AWS Command Line Interface (AWS CLI), use the aws cloudfront create-origin-request-policy command. You can use an input file to provide the command's input parameters, rather than specifying each individual parameter as command line input. To create an origin request policy (CLI with input file) 1. Use the following command to create a file named origin-request-policy.yaml that contains all of the input parameters for the create-origin-request-policy command. aws cloudfront create-origin-request-policy --generate-cli-skeleton yaml-input > origin-request-policy.yaml 2. Open the file named origin-request-policy.yaml that you just created. Edit the file to specify the origin request policy settings that you want, then save the file. You can remove optional fields from the file, but don't remove the required fields. For more information about the origin request policy settings, see Understand origin request policies. 3. Use the following command to create the origin request policy using input parameters from the origin-request-policy.yaml file. aws cloudfront create-origin-request-policy --cli-input-yaml file://origin- request-policy.yaml Create origin request policies 240 Amazon CloudFront Developer Guide Make note of the Id value in the command's output. This is the origin request policy ID, and you need it to attach the origin request policy to a CloudFront distribution's cache behavior. To attach an origin request policy to an existing distribution (CLI with input file) 1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to update. Replace distribution_ID with the distribution's ID. aws cloudfront get-distribution-config --id distribution_ID --output yaml > dist-config.yaml 2. Open the file named dist-config.yaml that you just created. Edit the file, making the following changes to each cache behavior that you are updating to use an origin request policy. • In the cache behavior, add a field named OriginRequestPolicyId. For the field's value, use the origin request policy ID that you noted after creating the policy. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the distribution to use the origin request policy. Replace distribution_ID with the distribution's ID. aws cloudfront update-distribution --id distribution_ID --cli-input-yaml file:// dist-config.yaml To attach an origin request policy to a new distribution (CLI with input file) 1. Use the following command to create a file named distribution.yaml that contains all of the input parameters for the create-distribution command. aws cloudfront create-distribution --generate-cli-skeleton yaml-input > distribution.yaml Create origin request policies 241 Amazon CloudFront Developer Guide 2. Open the file named distribution.yaml that you just created. In the default cache behavior, in the OriginRequestPolicyId field, enter the origin request policy ID that you noted after creating the policy. Continue editing the file to specify the distribution settings that you want, then save the file when finished. For more information about the distribution settings, see Distribution settings reference. 3. Use the following command to create the distribution using input parameters from the distribution.yaml file. aws cloudfront create-distribution --cli-input-yaml file://distribution.yaml API To create an origin request policy with the CloudFront API, use CreateOriginRequestPolicy. For more information |
AmazonCloudFront_DevGuide-097 | AmazonCloudFront_DevGuide.pdf | 97 | Developer Guide 2. Open the file named distribution.yaml that you just created. In the default cache behavior, in the OriginRequestPolicyId field, enter the origin request policy ID that you noted after creating the policy. Continue editing the file to specify the distribution settings that you want, then save the file when finished. For more information about the distribution settings, see Distribution settings reference. 3. Use the following command to create the distribution using input parameters from the distribution.yaml file. aws cloudfront create-distribution --cli-input-yaml file://distribution.yaml API To create an origin request policy with the CloudFront API, use CreateOriginRequestPolicy. For more information about the fields that you specify in this API call, see Understand origin request policies and the API reference documentation for your AWS SDK or other API client. After you create an origin request policy, you can attach it to a cache behavior, using one of the following API calls: • To attach it to a cache behavior in an existing distribution, use UpdateDistribution. • To attach it to a cache behavior in a new distribution, use CreateDistribution. For both of these API calls, provide the origin request policy's ID in the OriginRequestPolicyId field, inside a cache behavior. For more information about the other fields that you specify in these API calls, see Distribution settings reference and the API reference documentation for your AWS SDK or other API client. Use managed origin request policies CloudFront provides a set of managed origin request policies that you can attach to any of your distribution's cache behaviors. With a managed origin request policy, you don't need to write or maintain your own origin request policy. The managed policies use settings that are optimized for specific use cases. Use managed origin request policies 242 Amazon CloudFront Developer Guide To use a managed origin request policy, you attach it to a cache behavior in your distribution. The process is the same as when you create an origin request policy, but instead of creating a new one, you just attach one of the managed origin request policies. You attach the policy either by name (with the console) or by ID (with the AWS CLI or SDKs). The names and IDs are listed in the following section. For more information, see Create origin request policies. The following topics describe the managed origin request policies that you can use. Topics • AllViewer • AllViewerAndCloudFrontHeaders-2022-06 • AllViewerExceptHostHeader • CORS-CustomOrigin • CORS-S3Origin • Elemental-MediaTailor-PersonalizedManifests • UserAgentRefererHeaders AllViewer View this policy in the CloudFront console This policy includes all values (headers, cookies, and query strings) from the viewer request. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 216adef6-5c7f-47e4-b989-5492eafa07d3 This policy has the following settings: • Headers included in origin requests: All headers in the viewer request • Cookies included in origin requests: All • Query strings included in origin requests: All AllViewerAndCloudFrontHeaders-2022-06 View this policy in the CloudFront console AllViewer 243 Amazon CloudFront Developer Guide This policy includes all values (headers, cookies, and query strings) from the viewer request, and all CloudFront headers that were released through June 2022 (CloudFront headers released after June 2022 are not included). When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 33f36d7e-f396-46d9-90e0-52428a34d9dc This policy has the following settings: • Headers included in origin requests: All headers in the viewer request, and the following CloudFront headers: • CloudFront-Forwarded-Proto • CloudFront-Is-Android-Viewer • CloudFront-Is-Desktop-Viewer • CloudFront-Is-IOS-Viewer • CloudFront-Is-Mobile-Viewer • CloudFront-Is-SmartTV-Viewer • CloudFront-Is-Tablet-Viewer • CloudFront-Viewer-Address • CloudFront-Viewer-ASN • CloudFront-Viewer-City • CloudFront-Viewer-Country • CloudFront-Viewer-Country-Name • CloudFront-Viewer-Country-Region • CloudFront-Viewer-Country-Region-Name • CloudFront-Viewer-Http-Version • CloudFront-Viewer-Latitude • CloudFront-Viewer-Longitude • CloudFront-Viewer-Metro-Code • CloudFront-Viewer-Postal-Code • CloudFront-Viewer-Time-Zone • CloudFront-Viewer-TLS • Cookies included in origin requests: All AllViewerAndCloudFrontHeaders-2022-06 244 Amazon CloudFront Developer Guide • Query strings included in origin requests: All AllViewerExceptHostHeader View this policy in the CloudFront console This policy does not include the Host header from the viewer request, but does include all others values (headers, cookies, and query strings) from the viewer request. This policy also includes additional CloudFront request headers for HTTP protocol, HTTP version, TLS version, and all device type and viewer location headers. This policy is intended for use with Amazon API Gateway and AWS Lambda function URL origins. These origins expect the Host header to contain the origin domain name, not the domain name of the CloudFront distribution. Forwarding the Host header from the viewer request to these origins can prevent them from working. Note When you use this managed origin request policy to remove the viewer's Host header, CloudFront adds a new Host header with the origin's domain name to the origin request. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: b689b0a8-53d0-40ab-baf2-68738e2966ac This policy has the following settings: • Headers included in origin requests: |
AmazonCloudFront_DevGuide-098 | AmazonCloudFront_DevGuide.pdf | 98 | Lambda function URL origins. These origins expect the Host header to contain the origin domain name, not the domain name of the CloudFront distribution. Forwarding the Host header from the viewer request to these origins can prevent them from working. Note When you use this managed origin request policy to remove the viewer's Host header, CloudFront adds a new Host header with the origin's domain name to the origin request. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: b689b0a8-53d0-40ab-baf2-68738e2966ac This policy has the following settings: • Headers included in origin requests: All headers in the viewer request except for the Host header • Cookies included in origin requests: All • Query strings included in origin requests: All CORS-CustomOrigin View this policy in the CloudFront console AllViewerExceptHostHeader 245 Amazon CloudFront Developer Guide This policy includes the header that enables cross-origin resource sharing (CORS) requests when the origin is a custom origin. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 59781a5b-3903-41f3-afcb-af62929ccde1 This policy has the following settings: • Headers included in origin requests: • Origin • Cookies included in origin requests: None • Query strings included in origin requests: None CORS-S3Origin View this policy in the CloudFront console This policy includes the headers that enable cross-origin resource sharing (CORS) requests when the origin is an Amazon S3 bucket. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 88a5eaf4-2fd4-4709-b370-b4c650ea3fcf This policy has the following settings: • Headers included in origin requests: • Origin • Access-Control-Request-Headers • Access-Control-Request-Method • Cookies included in origin requests: None • Query strings included in origin requests: None Elemental-MediaTailor-PersonalizedManifests View this policy in the CloudFront console CORS-S3Origin 246 Amazon CloudFront Developer Guide This policy is intended for use with an origin that is an AWS Elemental MediaTailor endpoint. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 775133bc-15f2-49f9-abea-afb2e0bf67d2 This policy has the following settings: • Headers included in origin requests: • Origin • Access-Control-Request-Headers • Access-Control-Request-Method • User-Agent • X-Forwarded-For • Cookies included in origin requests: None • Query strings included in origin requests: All UserAgentRefererHeaders View this policy in the CloudFront console This policy includes only the User-Agent and Referer headers. It doesn't include any query strings or cookies. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: acba4595-bd28-49b8-b9fe-13317c0390fa This policy has the following settings: • Headers included in origin requests: • User-Agent • Referer • Cookies included in origin requests: None • Query strings included in origin requests: None UserAgentRefererHeaders 247 Amazon CloudFront Developer Guide Add CloudFront request headers You can configure CloudFront to add specific HTTP headers to the requests that CloudFront receives from viewers and forwards on to your origin or edge function. The values of these HTTP headers are based on characteristics of the viewer or the viewer request. The headers provide information about the viewer's device type, IP address, geographic location, request protocol (HTTP or HTTPS), HTTP version, TLS connection details, JA3 fingerprint, and JA4 fingerprint. You can also configure your distribution's cache behavior to forward WebSocket headers. For more information, see Use WebSockets with CloudFront distributions. With these headers, your origin or your edge function can receive information about the viewer without the need for you to write your own code to determine this information. If your origin returns different responses based on the information in these headers, you can include them in the cache key so that CloudFront caches the responses separately. For example, your origin might respond with content in a specific language based on the country that the viewer is in, or with content tailored to a specific device type. Your origin might also write these headers to log files, which you can use to determine information about where your viewers are, which device types they're on, and more. To include these headers in the cache key, use a cache policy. For more information, see Control the cache key with a policy and the section called “Understand the cache key”. To receive these headers at your origin but not include them in the cache key, use an origin request policy. For more information, see Control origin requests with a policy. Topics • Device type headers • Viewer location headers • Headers to determine the viewer's header structure • TLS-related headers • Other CloudFront headers Device type headers You can add the following headers to determine the viewer's device type. Based on the value of the User-Agent header, CloudFront sets the value of these headers to true or false. If a device falls into more than one category, more than one value can be true. For example, for |
AmazonCloudFront_DevGuide-099 | AmazonCloudFront_DevGuide.pdf | 99 | but not include them in the cache key, use an origin request policy. For more information, see Control origin requests with a policy. Topics • Device type headers • Viewer location headers • Headers to determine the viewer's header structure • TLS-related headers • Other CloudFront headers Device type headers You can add the following headers to determine the viewer's device type. Based on the value of the User-Agent header, CloudFront sets the value of these headers to true or false. If a device falls into more than one category, more than one value can be true. For example, for some tablet Add CloudFront request headers 248 Amazon CloudFront Developer Guide devices, CloudFront sets both CloudFront-Is-Mobile-Viewer and CloudFront-Is-Tablet- Viewer to true. • CloudFront-Is-Android-Viewer – Set to true when CloudFront determines that the viewer is a device with the Android operating system. • CloudFront-Is-Desktop-Viewer – Set to true when CloudFront determines that the viewer is a desktop device. • CloudFront-Is-IOS-Viewer – Set to true when CloudFront determines that the viewer is a device with an Apple mobile operating system, such as iPhone, iPod touch, and some iPad devices. • CloudFront-Is-Mobile-Viewer – Set to true when CloudFront determines that the viewer is a mobile device. • CloudFront-Is-SmartTV-Viewer – Set to true when CloudFront determines that the viewer is a smart TV. • CloudFront-Is-Tablet-Viewer – Set to true when CloudFront determines that the viewer is a tablet. Viewer location headers You can add the following headers to determine the viewer's location. CloudFront determines the values for these headers based on the viewer's IP address. For non-ASCII characters in these headers' values, CloudFront percent-encodes the character according to section 1.2 of RFC 3986. • CloudFront-Viewer-Address – Contains the IP address of the viewer and the source port of the request. For example, a header value of 198.51.100.10:46532 means the viewer's IP address is 198.51.100.10 and the request source port is 46532. • CloudFront-Viewer-ASN – Contains the autonomous system number (ASN) of the viewer. Note CloudFront-Viewer-Address and CloudFront-Viewer-ASN can be added in an origin request policy, but not in a cache policy. • CloudFront-Viewer-Country – Contains the two-letter country code for the viewer's country. For a list of country codes, see ISO 3166-1 alpha-2. • CloudFront-Viewer-City – Contains the name of the viewer's city. Viewer location headers 249 Amazon CloudFront Developer Guide When you add the following headers, CloudFront applies them to all requests except those that originate from the AWS network: • CloudFront-Viewer-Country-Name – Contains the name of the viewer's country. • CloudFront-Viewer-Country-Region – Contains a code (up to three characters) that represent the viewer's region. The region is the first-level subdivision (the broadest or least specific) of the ISO 3166-2 code. • CloudFront-Viewer-Country-Region-Name – Contains the name of the viewer's region. The region is the first-level subdivision (the broadest or least specific) of the ISO 3166-2 code. • CloudFront-Viewer-Latitude – Contains the viewer's approximate latitude. • CloudFront-Viewer-Longitude – Contains the viewer's approximate longitude. • CloudFront-Viewer-Metro-Code – Contains the viewer's metro code. This is present only when the viewer is in the United States. • CloudFront-Viewer-Postal-Code – Contains the viewer's postal code. • CloudFront-Viewer-Time-Zone Contains the viewer's time zone, in IANA time zone database format (for example, America/Los_Angeles). Note CloudFront-Viewer-City, CloudFront-Viewer-Metro-Code, and CloudFront- Viewer-Postal-Code might not be available for every IP address. Some IP addresses can't be geolocated with enough specificity to get that information. Headers to determine the viewer's header structure You can add the following headers to help identify the viewer based on the headers that it sends. For example, different browsers may send HTTP headers in a certain order. If the browser specified in the User-Agent header doesn’t match that browser’s expected header order, you can deny the request. Additionally, if the CloudFront-Viewer-Header-Count value does not match the number of headers in CloudFront-Viewer-Header-Order, you can deny the request. • CloudFront-Viewer-Header-Order – Contains the viewer's header names in the order requested, separated by a colon. For example: CloudFront-Viewer-Header-Order: Headers to determine the viewer's header structure 250 Amazon CloudFront Developer Guide Host:User-Agent:Accept:Accept-Encoding. Headers beyond the character limit of 7,680 are truncated. • CloudFront-Viewer-Header-Count – Contains the total number of the viewer's headers. TLS-related headers You can add the following headers to determine the viewer's JA3 fingerprint, JA4 fingerprint, and TLS connection details: • CloudFront-Viewer-JA3-Fingerprint – Contains the JA3 fingerprint of the viewer. The JA3 fingerprint can help you determine whether the request comes from a known client, whether that's malware or a malicious bot, or an expected (allow-listed) application. • CloudFront-Viewer-JA4-Fingerprint – Contains the JA4 fingerprint of the viewer. Similar to the JA3 fingerprint, the JA4 fingerprint can help you determine whether the request comes from a known client, whether that's malware or a malicious bot, or an expected (allow-listed) application. You can use the fingerprint to build a database of known good |
AmazonCloudFront_DevGuide-100 | AmazonCloudFront_DevGuide.pdf | 100 | viewer's JA3 fingerprint, JA4 fingerprint, and TLS connection details: • CloudFront-Viewer-JA3-Fingerprint – Contains the JA3 fingerprint of the viewer. The JA3 fingerprint can help you determine whether the request comes from a known client, whether that's malware or a malicious bot, or an expected (allow-listed) application. • CloudFront-Viewer-JA4-Fingerprint – Contains the JA4 fingerprint of the viewer. Similar to the JA3 fingerprint, the JA4 fingerprint can help you determine whether the request comes from a known client, whether that's malware or a malicious bot, or an expected (allow-listed) application. You can use the fingerprint to build a database of known good and bad actors to apply when inspecting HTTP requests. You can then inspect the header value on your application web servers or in your Lambda@Edge and CloudFront Functions to compare the header value against a list of known malware fingerprints to block malicious clients. • CloudFront-Viewer-TLS – Contains the SSL/TLS version, the cipher, and information about the SSL/TLS handshake that was used for the connection between the viewer and CloudFront. The header value is in the following format: SSL/TLS_version:cipher:handshake_information For handshake_information, the header can contain the following values: • fullHandshake – A full handshake was performed for the SSL/TLS session. • sessionResumed – A previous SSL/TLS session was resumed. • connectionReused – A previous SSL/TLS connection was reused. The following are some example values for this header: TLSv1.3:TLS_AES_128_GCM_SHA256:sessionResumed TLSv1.2:ECDHE-ECDSA-AES128-GCM-SHA256:connectionReused TLS-related headers 251 Amazon CloudFront Developer Guide TLSv1.1:ECDHE-RSA-AES128-SHA256:fullHandshake TLSv1:ECDHE-RSA-AES256-SHA:fullHandshake For the full list of possible SSL/TLS versions and ciphers that can be in this header value, see the section called “Supported protocols and ciphers between viewers and CloudFront”. Notes • The JA3 and JA4 fingerprints are derived from the SSL/TLS Client Hello packet. They are only present for HTTPS requests. • For these TLS-related headers, you can add them to a origin request policy, but not in a cache policy. Other CloudFront headers You can add the following headers to determine the viewer's original request URI, original request query string parameters and values, protocol, and version: • CloudFront-Error-Uri – Contains the original request URI that was received from the viewer. • CloudFront-Error-Args – Contains the original request query string parameters and values. • CloudFront-Forwarded-Proto – Contains the protocol of the viewer's request (HTTP or HTTPS). • CloudFront-Viewer-Http-Version – Contains the HTTP version of the viewer's request. Understand how origin request policies and cache policies work together You can use a CloudFront origin request policy to control the requests that CloudFront sends to the origin, which are called origin requests. To use an origin request policy, you must attach a cache policy to the same cache behavior. You cannot use an origin request policy in a cache behavior without a cache policy. For more information, see Control origin requests with a policy. Other CloudFront headers 252 Amazon CloudFront Developer Guide Origin request policies and cache policies work together to determine the values that CloudFront includes in origin requests. All URL query strings, HTTP headers, and cookies that you specify in the cache key (using a cache policy) are automatically included in origin requests. Any additional query strings, headers, and cookies that you specify in an origin request policy are also included in origin requests (but not in the cache key). Origin request policies and cache policies have settings that might appear to conflict with each other. For example, one policy might allow certain values while another policy blocks them. The following table explains which values CloudFront includes in origin requests when you use the settings of an origin request policy and a cache policy together. These settings generally apply to all types of values (query strings, headers, and cookies), with the exception that you cannot specify all headers or use a header block list in a cache policy. Cache policy None Origin request policy None All Allow list Block list No values from the viewer All values from the viewer Only the values specified in the request are request are origin request included in the included in the policy are All values from the viewer request except those specified origin request, origin request. included in the in the origin origin request. request policy are included in the origin request. except for the defaults that are included in every origin request. For more informati on, see Control origin requests with a policy. All Note: You cannot specify All query strings and cookies from the viewer All values from the viewer request are All query strings and cookies from the viewer All query strings and cookies from the viewer request are request, and request are Understand how origin request policies and cache policies work together 253 Amazon CloudFront Developer Guide Origin request policy None All Allow list Block list all headers in a included in the included in the any headers included in the |
AmazonCloudFront_DevGuide-101 | AmazonCloudFront_DevGuide.pdf | 101 | defaults that are included in every origin request. For more informati on, see Control origin requests with a policy. All Note: You cannot specify All query strings and cookies from the viewer All values from the viewer request are All query strings and cookies from the viewer All query strings and cookies from the viewer request are request, and request are Understand how origin request policies and cache policies work together 253 Amazon CloudFront Developer Guide Origin request policy None All Allow list Block list all headers in a included in the included in the any headers included in the cache policy. origin request. origin request. specified in the origin request origin request, even those policy, are specified in the included in the origin request origin request. policy block list. The cache policy setting overrides the origin request policy block list. Allow list Only the specified values All values from the viewer All values specified in the The values specified in the from the viewer request are cache policy cache policy are request are included in the or the origin included in the included in the origin request. request policy origin request, origin request. are included in the origin request. even if those same values are specified in the origin request policy block list. The cache policy allow list overrides the origin request policy block list. Understand how origin request policies and cache policies work together 254 Amazon CloudFront Developer Guide Origin request policy None All Allow list Block list All query strings and cookies All values from the viewer The values specified in the Block list Note: You cannot specify headers in a cache policy block list. from the viewer request except those specified are included in the origin request. All values from the viewer request except those specified request are origin request included in the policy are origin request. included in the in the cache origin request, policy or the even if those origin request same values are policy are specified in the included in the cache policy origin request. block list. The origin request policy allow list overrides the cache policy block list. Understand how origin request policies and cache policies work together 255 Amazon CloudFront Developer Guide Add or remove HTTP headers in CloudFront responses with a policy You can configure CloudFront to modify the HTTP headers in the responses that it sends to viewers (web browsers and other clients). CloudFront can remove headers that it received from the origin, or add headers to the response, before sending the response to viewers. Making these changes doesn't require writing code or changing the origin. For example, you can remove headers such as X-Powered-By and Vary so that CloudFront doesn't include these headers in the responses that it sends to viewers. Or, you can add HTTP headers such as the following: • A Cache-Control header to control browser caching. • An Access-Control-Allow-Origin header to enable cross-origin resource sharing (CORS). You can also add other CORS headers. • A set of common security headers, such as Strict-Transport-Security, Content- Security-Policy, and X-Frame-Options. • A Server-Timing header to see information that's related to the performance and routing of both the request and response through CloudFront. To specify the headers that CloudFront adds or removes in HTTP responses, you use a response headers policy. You attach a response headers policy to one more cache behaviors, and CloudFront modifies the headers in the responses that it sends to requests that match the cache behavior. CloudFront modifies the headers in the responses that it serves from the cache and the ones that it forwards from the origin. If the origin response includes one or more of the headers that are added in a response headers policy, the policy can specify if CloudFront uses the header it received from the origin or overwrites that header with the one in the response headers policy. Note If you add headers that control browser caching to your response header policies, such as Cache-Control, CloudFront adds these headers to the viewer response only. These headers don't affect how CloudFront caches the requested object. 256 Amazon CloudFront Developer Guide CloudFront provides predefined response headers policies, known as managed policies, for common use cases. You can use these managed policies or create your own policies. You can attach a single response headers policy to multiple cache behaviors in multiple distributions in your AWS account. For more information, see the following: Topics • Understand response headers policies • Create response headers policies • Use managed response headers policies Understand response headers policies You can use a response headers policy to specify the HTTP headers that Amazon CloudFront removes or adds in responses that it sends to viewers. For more information about response headers policies and reasons to use them, see Add or |
AmazonCloudFront_DevGuide-102 | AmazonCloudFront_DevGuide.pdf | 102 | common use cases. You can use these managed policies or create your own policies. You can attach a single response headers policy to multiple cache behaviors in multiple distributions in your AWS account. For more information, see the following: Topics • Understand response headers policies • Create response headers policies • Use managed response headers policies Understand response headers policies You can use a response headers policy to specify the HTTP headers that Amazon CloudFront removes or adds in responses that it sends to viewers. For more information about response headers policies and reasons to use them, see Add or remove response headers with a policy. The following topics explain the settings in a response headers policy. The settings are grouped into categories, which are represented in the following topics. Topics • Policy details (metadata) • CORS headers • Security headers • Custom headers • Remove headers • Server-Timing header Policy details (metadata) The policy details settings contain metadata about a response headers policy. • Name – A name to identify the response headers policy. In the console, you use the name to attach the policy to a cache behavior. • Description (optional) – A comment to describe the response headers policy. This is optional, but it can help you identify the purpose of the policy. Understand response headers policies 257 Amazon CloudFront CORS headers Developer Guide The cross-origin resource sharing (CORS) settings allow you to add and configure CORS headers in a response headers policy. This list focuses on how to specify settings and valid values in a response headers policy. For more information about each of these headers and how they're used for real-world CORS requests and responses, see cross-origin resource sharing in the MDN Web Docs and the CORS protocol spec. Access-Control-Allow-Credentials This is a Boolean setting (true or false) that determines if CloudFront adds the Access- Control-Allow-Credentials header in responses to CORS requests. When this setting is set to true, CloudFront adds the Access-Control-Allow-Credentials: true header in responses to CORS requests. Otherwise, CloudFront doesn't add this header to responses. Access-Control-Allow-Headers Specifies the header names that CloudFront uses as values for the Access-Control-Allow- Headers header in responses to CORS preflight requests. Valid values for this setting include HTTP header names or the wildcard character (*), which indicates that all headers are allowed. Note The Authorization header can't use a wildcard and must be listed explicitly. Examples of valid use of the wildcard character Example x-amz-* Will match Will not match x-amz-test x-amz x-amz- x-*-amz x-test-amz * CORS headers x--amz All headers except Authorization Authorization 258 Amazon CloudFront Access-Control-Allow-Methods Developer Guide Specifies the HTTP methods that CloudFront uses as values for the Access-Control-Allow- Methods header in responses to CORS preflight requests. Valid values are GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT, and ALL. ALL is a special value that includes all of the listed HTTP methods. Access-Control-Allow-Origin Specifies the values that CloudFront can use in the Access-Control-Allow-Origin response header. Valid values for this setting include a specific origin (such as http:// www.example.com) or the wildcard character (*), which indicates that all origins are allowed. Notes • The wildcard character (*) is allowed as the leftmost subdomain (*.example.org). • The wildcard character (*) isn't allowed in the following positions: • Top-level domains (example.*) • To the right of subdomains (test.*.example.org) or within any subdomains (*test.example.org) • Inside of terms (exa*mple.org) For examples of ways to use the wildcard character, see the following table. Example Will match Will not match http://*.example.org http://www.example .org http://test.exampl e.org https://test.e xample.org https://test.e xample.org:123 http://test.exampl e.org:123 *.example.org test.example.org http://test.exampl e.org:123 CORS headers 259 Amazon CloudFront Developer Guide Example Will match Will not match test.test.example. https://test.examp org le.org:123 .example.org http://test.exampl e.org https://test.examp le.org example.org http://example.org https://example.org http://example.org http://example.org:* http://example.org :123 http://example.org http://example.org http://example.org :1*3 :123 http://example.org :1893 http://example.org :13 *.example.org:1* test.example.org:123 https://example.org http://example.org :123 CORS headers 260 Amazon CloudFront Access-Control-Expose-Headers Developer Guide Specifies the header names that CloudFront uses as values for the Access-Control-Expose- Headers header in responses to CORS requests. Valid values for this setting include HTTP header names or the wildcard character (*). Access-Control-Max-Age A number of seconds, which CloudFront uses as the value for the Access-Control-Max-Age header in responses to CORS preflight requests. Origin override A Boolean setting that determines how CloudFront behaves when the response from the origin contains one of the CORS headers that's also in the policy. • When set to true and the origin response contains a CORS header that's also in the policy, CloudFront adds the CORS header in the policy to the response. CloudFront then sends that response to the viewer. CloudFront ignores the header that it received from the origin. • When set to false and the origin response contains a CORS header (regardless of whether the CORS header is in the policy), CloudFront includes the |
AmazonCloudFront_DevGuide-103 | AmazonCloudFront_DevGuide.pdf | 103 | Origin override A Boolean setting that determines how CloudFront behaves when the response from the origin contains one of the CORS headers that's also in the policy. • When set to true and the origin response contains a CORS header that's also in the policy, CloudFront adds the CORS header in the policy to the response. CloudFront then sends that response to the viewer. CloudFront ignores the header that it received from the origin. • When set to false and the origin response contains a CORS header (regardless of whether the CORS header is in the policy), CloudFront includes the CORS header that it received from the origin to the response. CloudFront doesn't add any CORS headers in the policy to the response that is sent to the viewer. Security headers You can use the security headers settings to add and configure several security-related HTTP response headers in a response headers policy. This list describes how you can specify settings and valid values in a response headers policy. For more information about each of these headers and how they're used in real-world HTTP responses, see the links to the MDN Web Docs. Content-Security-Policy Specifies the content security policy directives that CloudFront uses as values for the Content- Security-Policy response header. For more information about this header and valid policy directives, see Content-Security-Policy in the MDN Web Docs. Security headers 261 Amazon CloudFront Note Developer Guide The Content-Security-Policy header value is limited to 1783 characters. Referrer-Policy Specifies the referrer policy directive that CloudFront uses as the value for the Referrer- Policy response header. Valid values for this setting are no-referrer, no-referrer- when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, and unsafe-url. For more information about this header and these directives, see Referrer-Policy in the MDN Web Docs. Strict-Transport-Security Specifies the directives and settings that CloudFront uses as the value for the Strict- Transport-Security response header. For this setting, you separately specify: • A number of seconds, which CloudFront uses as the value for the max-age directive of this header • A Boolean setting (true or false) for preload, which determines whether CloudFront includes the preload directive in the value of this header • A Boolean setting (true or false) for includeSubDomains, which determines whether CloudFront includes the includeSubDomains directive in the value of this header For more information about this header and these directives, see Strict-Transport-Security in the MDN Web Docs. X-Content-Type-Options This is a Boolean setting (true or false) that determines if CloudFront adds the X-Content- Type-Options header to responses. When this setting is true, CloudFront adds the X- Content-Type-Options: nosniff header to responses. Otherwise CloudFront doesn't add this header. For more information about this header, see X-Content-Type-Options in the MDN Web Docs. Security headers 262 Amazon CloudFront X-Frame-Options Developer Guide Specifies the directive that CloudFront uses as the value for the X-Frame-Options response header. Valid values for this setting are DENY or SAMEORIGIN. For more information about this header and these directives, see X-Frame-Options in the MDN Web Docs. X-XSS-Protection Specifies the directives and settings that CloudFront uses as the value for the X-XSS- Protection response header. For this setting, you separately specify: • An X-XSS-Protection setting of 0 (disables XSS filtering) or 1 (enables XSS filtering) • A Boolean setting (true or false) for block, which determines whether CloudFront includes the mode=block directive in the value for this header • A reporting URI, which determines whether CloudFront includes the report=reporting URI directive in the value for this header You can specify true for block, or you can specify a reporting URI, but you can't specify both together. For more information about this header and these directives, see X-XSS-Protection in the MDN Web Docs. Origin override Each of these security headers settings contains a Boolean setting (true or false) that determines how CloudFront behaves when the response from the origin contains that header. When this setting is set to true and the origin response contains the header, CloudFront adds the header in the policy to the response that it sends to the viewer. It ignores the header that it received from the origin. When this setting is set to false and the origin response contains the header, CloudFront includes the header that it received from the origin in the response that it sends to the viewer. When the origin response doesn't contain the header, CloudFront adds the header in the policy to the response that it sends to the viewer. CloudFront does this when this setting is set to true or false. Security headers 263 Amazon CloudFront Custom headers Developer Guide You can use custom headers settings to add and configure custom HTTP headers in a response headers policy. CloudFront adds these headers to every response that it returns to viewers. For each custom header, you also specify the value for |
AmazonCloudFront_DevGuide-104 | AmazonCloudFront_DevGuide.pdf | 104 | that it received from the origin in the response that it sends to the viewer. When the origin response doesn't contain the header, CloudFront adds the header in the policy to the response that it sends to the viewer. CloudFront does this when this setting is set to true or false. Security headers 263 Amazon CloudFront Custom headers Developer Guide You can use custom headers settings to add and configure custom HTTP headers in a response headers policy. CloudFront adds these headers to every response that it returns to viewers. For each custom header, you also specify the value for the header, though specifying a value is optional. This is because CloudFront can add a response header with no value. Each custom header also has its own Origin override setting: • When this setting is set to true and the origin response contains the custom header that's in the policy, CloudFront adds the custom header in the policy to the response that it sends to the viewer. It ignores the header that it received from the origin. • When this setting is false and the origin response contains the custom header that's in the policy, CloudFront includes the custom header that it received from the origin in the response that it sends to the viewer. • When the origin response doesn't contain the custom header that's in the policy, CloudFront adds the custom header in the policy to the response that it sends to the viewer. CloudFront does this when this setting is set to true or false. Remove headers You can specify headers that you want CloudFront to remove from the responses it receives from the origin so the headers are not included in the responses that CloudFront sends to viewers. CloudFront removes the headers from every response it sends to viewers, whether the objects is served from CloudFront's cache or from the origin. For example, you can remove headers that are of no use to browsers, such as X-Powered-By or Vary, so that CloudFront removes these headers from the responses that it sends to viewers. When you specify headers to remove using a response headers policy, CloudFront removes the headers first and then adds any headers that are specified in other sections of the response headers policy (CORS headers, security headers, custom headers, etc.). If you specify a header to remove but also add the same header in another section of the policy, CloudFront includes the header in the responses that it sends to viewers. Note You can use a response headers policy to remove the Server and Date headers that CloudFront received from the origin, so that these headers (as received from the origin) are Custom headers 264 Amazon CloudFront Developer Guide not included in the responses that CloudFront sends to viewers. However, if you do that, CloudFront adds its own version of these headers to responses that it sends to viewers. For the Server header that CloudFront adds, the header's value is CloudFront. Headers that you can't remove You cannot remove the following headers using a response headers policy. If you specify these headers in the Remove headers section of a response headers policy (ResponseHeadersPolicyRemoveHeadersConfig in the API), you receive an error. • Connection • Content-Encoding • Content-Length • Expect • Host • Keep-Alive • Proxy-Authenticate • Proxy-Authorization • Proxy-Connection • Trailer • Transfer-Encoding • Upgrade • Via • Warning • X-Accel-Buffering • X-Accel-Charset • X-Accel-Limit-Rate • X-Accel-Redirect • X-Amz-Cf-.* • X-Amzn-Auth Remove headers 265 Developer Guide Amazon CloudFront • X-Amzn-Cf-Billing • X-Amzn-Cf-Id • X-Amzn-Cf-Xff • X-Amzn-ErrorType • X-Amzn-Fle-Profile • X-Amzn-Header-Count • X-Amzn-Header-Order • X-Amzn-Lambda-Integration-Tag • X-Amzn-RequestId • X-Cache • X-Edge-.* • X-Forwarded-Proto • X-Real-Ip Server-Timing header Use the Server-Timing header setting to enable the Server-Timing header in HTTP responses sent from CloudFront. You can use this header to view metrics that can help you gain insights about the behavior and performance of CloudFront and your origin. For example, you can see which cache layer served a cache hit. Or, you can see the first byte latency from the origin if there's a cache miss. The metrics in the Server-Timing header can help you troubleshoot issues or test the efficiency of your CloudFront or origin configuration. For more information about using the Server-Timing header with CloudFront, see the following topics. To enable the Server-Timing header, create (or edit) a response headers policy. Topics • Sampling rate and Pragma request header • Server-Timing header from the origin • Server-Timing header metrics • Server-Timing header examples Server-Timing header 266 Amazon CloudFront Developer Guide Sampling rate and Pragma request header When you enable the Server-Timing header in a response headers policy, you also specify the sampling rate. The sampling rate is a number 0–100 (inclusive) that specifies the percentage of responses that you want CloudFront to add the Server-Timing |
AmazonCloudFront_DevGuide-105 | AmazonCloudFront_DevGuide.pdf | 105 | For more information about using the Server-Timing header with CloudFront, see the following topics. To enable the Server-Timing header, create (or edit) a response headers policy. Topics • Sampling rate and Pragma request header • Server-Timing header from the origin • Server-Timing header metrics • Server-Timing header examples Server-Timing header 266 Amazon CloudFront Developer Guide Sampling rate and Pragma request header When you enable the Server-Timing header in a response headers policy, you also specify the sampling rate. The sampling rate is a number 0–100 (inclusive) that specifies the percentage of responses that you want CloudFront to add the Server-Timing header to. When you set the sampling rate to 100, CloudFront adds the Server-Timing header to the HTTP response for every request that matches the cache behavior that the response headers policy is attached to. When you set it to 50, CloudFront adds the header to 50% of the responses for requests that match the cache behavior. You can set the sampling rate to any number 0–100 with up to four decimal places. When the sampling rate is set to a number lower than 100, you can't control which responses CloudFront adds the Server-Timing header to, only the percentage. However, you can add the Pragma header with a value set to server-timing in an HTTP request to receive the Server- Timing header in the response to that request. This works no matter what the sampling rate is set to. Even when the sampling rate is set to zero (0), CloudFront adds the Server-Timing header to the response if the request contains the Pragma: server-timing header. Server-Timing header from the origin When there is a cache miss and CloudFront forwards the request to the origin, the origin might include a Server-Timing header in its response to CloudFront. In this case, CloudFront adds its metrics to the Server-Timing header that it received from the origin. The response that CloudFront sends to the viewer contains a single Server-Timing header that includes the value that came from the origin and the metrics that CloudFront added. The header value from the origin might be at the end, or in between two sets of metrics that CloudFront adds to the header. When there is a cache hit, the response that CloudFront sends to the viewer contains a single Server-Timing header that includes only the CloudFront metrics in the header value (the value from the origin is not included). Server-Timing header metrics When CloudFront adds the Server-Timing header to an HTTP response, the value of the header contains one or more metrics that can help you gain insights about the behavior and performance of CloudFront and your origin. The following list contains all the metrics and their potential values. A Server-Timing header contains only some of these metrics, depending on the nature of the request and response through CloudFront. Server-Timing header 267 Amazon CloudFront Developer Guide Some of these metrics are included in the Server-Timing header with a name only (no value). Others are a name and a value. When a metric has a value, the name and value are separated by a semicolon (;). When the header contains more than one metric, the metrics are separated by a comma (,). cdn-cache-hit CloudFront provided a response from the cache without making a request to the origin. cdn-cache-refresh CloudFront provided a response from the cache after sending a request to the origin to verify that the cached object is still valid. In this case, CloudFront didn't retrieve the full object from the origin. cdn-cache-miss CloudFront didn't provide the response from the cache. In this case, CloudFront requested the full object from the origin before returning the response. cdn-pop Contains a value that describes which CloudFront point of presence (POP) handled the request. cdn-rid Contains a value with the CloudFront unique identifier for the request. You can use this request identifier (RID) when troubleshooting issues with Support cdn-hit-layer This metric is present when CloudFront provides a response from the cache without making a request to the origin. It contains one of the following values: • EDGE – CloudFront provided the cached response from a POP location. • REC – CloudFront provided the cached response from a regional edge cache (REC) location. • Origin Shield – CloudFront provided the cached response from the REC that's acting as Origin Shield. cdn-upstream-layer When CloudFront requests the full object from the origin, this metric is present and contains one of the following values: • EDGE – A POP location sent the request directly to the origin. Server-Timing header 268 Amazon CloudFront Developer Guide • REC – A REC location sent the request directly to the origin. • Origin Shield – The REC that's acting as Origin Shield sent the request directly to the origin. cdn-upstream-dns Contains a value with the number of milliseconds |
AmazonCloudFront_DevGuide-106 | AmazonCloudFront_DevGuide.pdf | 106 | (REC) location. • Origin Shield – CloudFront provided the cached response from the REC that's acting as Origin Shield. cdn-upstream-layer When CloudFront requests the full object from the origin, this metric is present and contains one of the following values: • EDGE – A POP location sent the request directly to the origin. Server-Timing header 268 Amazon CloudFront Developer Guide • REC – A REC location sent the request directly to the origin. • Origin Shield – The REC that's acting as Origin Shield sent the request directly to the origin. cdn-upstream-dns Contains a value with the number of milliseconds that were spent retrieving the DNS record for the origin. A value of zero (0) indicates that CloudFront used a cached DNS result or reused an existing connection. cdn-upstream-connect Contains a value with the number of milliseconds between when the origin DNS request completed and a TCP (and TLS, if applicable) connection to the origin completed. A value of zero (0) indicates that CloudFront reused an existing connection. cdn-upstream-fbl Contains a value with the number of milliseconds between when the origin HTTP request is completed and when the first byte is received in the response from the origin (first byte latency). cdn-downstream-fbl Contains a value with the number of milliseconds between when the edge location finished receiving the request and when it sent the first byte of the response to the viewer. Server-Timing header examples The following are examples of a Server-Timing header that a viewer might receive from CloudFront when the Server-Timing header setting is enabled. Example – cache miss The following example shows a Server-Timing header that a viewer might receive when the requested object is not in the CloudFront cache. Server-Timing: cdn-upstream-layer;desc="EDGE",cdn-upstream-dns;dur=0,cdn-upstream- connect;dur=114,cdn-upstream-fbl;dur=177,cdn-cache-miss,cdn-pop;desc="PHX50-C2",cdn- rid;desc="yNPsyYn7skvTzwWkq3Wcc8Nj_foxUjQUe9H1ifslzWhb0w7aLbFvGg==",cdn-downstream- fbl;dur=436 This Server-Timing header indicates the following: Server-Timing header 269 Amazon CloudFront Developer Guide • The origin request was sent from a CloudFront point of presence (POP) location (cdn- upstream-layer;desc="EDGE"). • CloudFront used a cached DNS result for the origin (cdn-upstream-dns;dur=0). • It took 114 milliseconds for CloudFront to complete the TCP (and TLS, if applicable) connection to the origin (cdn-upstream-connect;dur=114). • It took 177 milliseconds for CloudFront to receive the first byte of the response from the origin, after completing the request (cdn-upstream-fbl;dur=177). • The requested object wasn't in CloudFront's cache (cdn-cache-miss). • The request was received at the edge location identified by the code PHX50-C2 (cdn- pop;desc="PHX50-C2"). • The CloudFront unique ID for this request was yNPsyYn7skvTzwWkq3Wcc8Nj_foxUjQUe9H1ifslzWhb0w7aLbFvGg== (cdn- rid;desc="yNPsyYn7skvTzwWkq3Wcc8Nj_foxUjQUe9H1ifslzWhb0w7aLbFvGg=="). • It took 436 milliseconds for CloudFront to send the first byte of the response to the viewer, after receiving the viewer request (cdn-downstream-fbl;dur=436). Example – cache hit The following example shows a Server-Timing header that a viewer might receive when the requested object is in CloudFront's cache. Server-Timing: cdn-cache-hit,cdn-pop;desc="SEA19-C1",cdn- rid;desc="nQBz4aJU2kP9iC3KHEq7vFxfMozu-VYBwGzkW9diOpeVc7xsrLKj-g==",cdn-hit- layer;desc="REC",cdn-downstream-fbl;dur=137 This Server-Timing header indicates the following: • The requested object was in the cache (cdn-cache-hit). • The request was received at the edge location identified by the code SEA19-C1 (cdn- pop;desc="SEA19-C1"). • The CloudFront unique ID for this request was nQBz4aJU2kP9iC3KHEq7vFxfMozu- VYBwGzkW9diOpeVc7xsrLKj-g== (cdn-rid;desc="nQBz4aJU2kP9iC3KHEq7vFxfMozu- VYBwGzkW9diOpeVc7xsrLKj-g=="). • The requested object was cached in a regional edge cache (REC) location (cdn-hit- layer;desc="REC"). Server-Timing header 270 Amazon CloudFront Developer Guide • It took 137 milliseconds for CloudFront to send the first byte of the response to the viewer, after receiving the viewer request (cdn-downstream-fbl;dur=137). Create response headers policies You can use a response headers policy to specify the HTTP headers that Amazon CloudFront adds or removes in HTTP responses. For more information about response headers policies and reasons to use them, see Add or remove response headers with a policy. You can create a response headers policy in the CloudFront console. Or you can create one by using AWS CloudFormation, the AWS Command Line Interface (AWS CLI), or the CloudFront API. After you create a response headers policy, you attach it to one or more cache behaviors in a CloudFront distribution. Before you create a custom response headers policy, check if one of the managed response headers policies fits your use case. If one does, you can attach it to your cache behavior. That way, you don't need to create or manage your own response headers policy. Console To create a response headers policy (console) 1. Sign in to the AWS Management Console, then go to the Response headers tab on the Policies page in the CloudFront console at https://console.aws.amazon.com/cloudfront/ v4/home#/policies/responseHeaders. 2. Choose Create response headers policy. 3. In the Create response headers policy form, do the following: a. b. In the Details panel, enter a Name for the response headers policy and (optionally) a Description that explains what the policy is for. In the Cross-origin resource sharing (CORS) panel, choose the Configure CORS toggle and configure any CORS headers that you want to add to the policy. If you want the configured headers |
AmazonCloudFront_DevGuide-107 | AmazonCloudFront_DevGuide.pdf | 107 | (console) 1. Sign in to the AWS Management Console, then go to the Response headers tab on the Policies page in the CloudFront console at https://console.aws.amazon.com/cloudfront/ v4/home#/policies/responseHeaders. 2. Choose Create response headers policy. 3. In the Create response headers policy form, do the following: a. b. In the Details panel, enter a Name for the response headers policy and (optionally) a Description that explains what the policy is for. In the Cross-origin resource sharing (CORS) panel, choose the Configure CORS toggle and configure any CORS headers that you want to add to the policy. If you want the configured headers to override the headers that CloudFront receives from the origin, select the Origin override check box. For more information about the CORS headers settings, see the section called “CORS headers”. Create response headers policies 271 Amazon CloudFront Developer Guide c. In the Security headers panel, choose the toggle and configure each of the security headers that you want to add to the policy. For more information about the security headers settings, see the section called “Security headers”. d. In the Custom headers panel, add any custom headers that you want to include in the policy. For more information about the custom headers settings, see the section called “Custom headers”. e. In the Remove headers panel, add the names of any headers that you want CloudFront to remove from the origin's response and not include in the response that CloudFront sends to viewers. For more information about the remove headers settings, see the section called “Remove headers”. f. In the Server-Timing header panel, choose the Enable toggle and enter a sampling rate (a number between 0 and 100, inclusive). For more information about the Server-Timing header, see the section called “Server-Timing header”. 4. Choose Create to create the policy. After you create a response headers policy, you can attach it to a cache behavior in a CloudFront distribution. To attach a response headers policy to an existing distribution (console) 1. Open the Distributions page in the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home#/distributions. 2. Choose the distribution to update, then choose the Behaviors tab. 3. Select the cache behavior to update, then choose Edit. Or, to create a new cache behavior, choose Create behavior. 4. For Response headers policy, choose the policy to add to the cache behavior. 5. Choose Save changes to update the cache behavior. If you're creating a new cache behavior, choose Create behavior. Create response headers policies 272 Amazon CloudFront Developer Guide To attach a response headers policy to a new distribution (console) 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose Create distribution. 3. For Response headers policy, choose the policy to add to the cache behavior. 4. Choose the other settings for your distribution. For more information, see the section called “Distribution settings”. 5. Choose Create distribution to create the distribution. AWS CloudFormation To create a response headers policy with AWS CloudFormation, use the AWS::CloudFront::ResponseHeadersPolicy resource type. The following example shows the AWS CloudFormation template syntax, in YAML format, for creating a response headers policy. Type: AWS::CloudFront::ResponseHeadersPolicy Properties: ResponseHeadersPolicyConfig: Name: EXAMPLE-Response-Headers-Policy Comment: Example response headers policy for the documentation CorsConfig: AccessControlAllowCredentials: false AccessControlAllowHeaders: Items: - '*' AccessControlAllowMethods: Items: - GET - OPTIONS AccessControlAllowOrigins: Items: - https://example.com - https://docs.example.com AccessControlExposeHeaders: Items: - '*' AccessControlMaxAgeSec: 600 OriginOverride: false CustomHeadersConfig: Create response headers policies 273 Amazon CloudFront Items: - Header: Example-Custom-Header-1 Value: value-1 Override: true - Header: Example-Custom-Header-2 Value: value-2 Override: true SecurityHeadersConfig: ContentSecurityPolicy: Developer Guide ContentSecurityPolicy: default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'; frame-ancestors 'none' Override: false ContentTypeOptions: # You don't need to specify a value for 'X-Content-Type- Options'. # Simply including it in the template sets its value to 'nosniff'. Override: false FrameOptions: FrameOption: DENY Override: false ReferrerPolicy: ReferrerPolicy: same-origin Override: false StrictTransportSecurity: AccessControlMaxAgeSec: 63072000 IncludeSubdomains: true Preload: true Override: false XSSProtection: ModeBlock: true # You can set ModeBlock to 'true' OR set a value for ReportUri, but not both Protection: true Override: false ServerTimingHeadersConfig: Enabled: true SamplingRate: 50 RemoveHeadersConfig: Items: - Header: Vary - Header: X-Powered-By For more information, see AWS::CloudFront::ResponseHeadersPolicy in the AWS CloudFormation User Guide. Create response headers policies 274 Amazon CloudFront CLI Developer Guide To create a response headers policy with the AWS Command Line Interface (AWS CLI), use the aws cloudfront create-response-headers-policy command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input. To create a response headers policy (CLI with input file) 1. Use the following command to create a file that's named response-headers- policy.yaml. This file contains all of the input parameters for the create-response- headers-policy command. aws cloudfront create-response-headers-policy --generate-cli-skeleton yaml-input > response-headers-policy.yaml 2. Open the response-headers-policy.yaml file that you just created. Edit the file to specify a policy name and the desired |
AmazonCloudFront_DevGuide-108 | AmazonCloudFront_DevGuide.pdf | 108 | the AWS Command Line Interface (AWS CLI), use the aws cloudfront create-response-headers-policy command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input. To create a response headers policy (CLI with input file) 1. Use the following command to create a file that's named response-headers- policy.yaml. This file contains all of the input parameters for the create-response- headers-policy command. aws cloudfront create-response-headers-policy --generate-cli-skeleton yaml-input > response-headers-policy.yaml 2. Open the response-headers-policy.yaml file that you just created. Edit the file to specify a policy name and the desired response headers policy configuration, then save the file. For more information about the response headers policy settings, see the section called “Understand response headers policies”. 3. Use the following command to create the response headers policy. The policy that you create uses the input parameters from the response-headers-policy.yaml file. aws cloudfront create-response-headers-policy --cli-input-yaml file://response- headers-policy.yaml Make note of the Id value in the command output. This is the response headers policy ID. You need it to attach the policy to the cache behavior of a CloudFront distribution. To attach a response headers policy to an existing distribution (CLI with input file) 1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to update. Replace distribution_ID with the distribution ID. Create response headers policies 275 Amazon CloudFront Developer Guide aws cloudfront get-distribution-config --id distribution_ID --output yaml > dist-config.yaml 2. Open the file that's named dist-config.yaml that you just created. Edit the file, making the following changes to the cache behavior to make it use the response headers policy. • In the cache behavior, add a field that's named ResponseHeadersPolicyId. For the field's value, use the response headers policy ID that you noted after creating the policy. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the distribution to use the response headers policy. Replace distribution_ID with the distribution ID. aws cloudfront update-distribution --id distribution_ID --cli-input-yaml file:// dist-config.yaml To attach a response headers policy to a new distribution (CLI with input file) 1. Use the following command to create a file that's named distribution.yaml. This file contains all of the input parameters for the create-distribution command. aws cloudfront create-distribution --generate-cli-skeleton yaml-input > distribution.yaml 2. Open the distribution.yaml file that you just created. In the default cache behavior, in the ResponseHeadersPolicyId field, enter the response headers policy ID that you noted after creating the policy. Continue editing the file to specify the distribution settings that you want, then save the file when finished. For more information about the distribution settings, see Distribution settings reference. 3. Use the following command to create the distribution using input parameters from the distribution.yaml file. Create response headers policies 276 Amazon CloudFront Developer Guide aws cloudfront create-distribution --cli-input-yaml file://distribution.yaml API To create a response headers policy with the CloudFront API, use CreateResponseHeadersPolicy. For more information about the fields that you specify in this API call, see the section called “Understand response headers policies” and the API reference documentation for your AWS SDK or other API client. After you create a response headers policy, you can attach it to a cache behavior, using one of the following API calls: • To attach it to a cache behavior in an existing distribution, use UpdateDistribution. • To attach it to a cache behavior in a new distribution, use CreateDistribution. For both of these API calls, provide the response headers policy ID in the ResponseHeadersPolicyId field, inside a cache behavior. For more information about the other fields that you specify in these API calls, see Distribution settings reference and the API reference documentation for your AWS SDK or other API client. Use managed response headers policies With a CloudFront response headers policy, you can specify the HTTP headers that Amazon CloudFront removes or adds in responses that it sends to viewers. For more information about response headers policies and reasons to use them, see Add or remove response headers with a policy. CloudFront provides managed response headers policies that you can attach to cache behaviors in your CloudFront distributions. With a managed response headers policy, you don't need to write or maintain your own policy. The managed policies contain sets of HTTP response headers for common use cases. To use a managed response headers policy, you attach it to a cache behavior in your distribution. The process is the same as when you create a custom response headers policy. However, instead of creating a new policy, you attach one of the managed policies. You attach the policy either by name (with the console) or by ID (with AWS CloudFormation, the AWS CLI, or the AWS SDKs). The names and |
AmazonCloudFront_DevGuide-109 | AmazonCloudFront_DevGuide.pdf | 109 | With a managed response headers policy, you don't need to write or maintain your own policy. The managed policies contain sets of HTTP response headers for common use cases. To use a managed response headers policy, you attach it to a cache behavior in your distribution. The process is the same as when you create a custom response headers policy. However, instead of creating a new policy, you attach one of the managed policies. You attach the policy either by name (with the console) or by ID (with AWS CloudFormation, the AWS CLI, or the AWS SDKs). The names and IDs are listed in the following section. Use managed response headers policies 277 Amazon CloudFront Developer Guide For more information, see the section called “Create response headers policies”. The following topics describe the managed response headers policies that you can use. Topics • CORS-and-SecurityHeadersPolicy • CORS-With-Preflight • CORS-with-preflight-and-SecurityHeadersPolicy • SecurityHeadersPolicy • SimpleCORS CORS-and-SecurityHeadersPolicy View this policy in the CloudFront console Use this managed policy to allow simple CORS requests from any origin. This policy also adds a set of security headers to all responses that CloudFront sends to viewers. This policy combines the the section called “SimpleCORS” and the section called “SecurityHeadersPolicy” policies into one. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: e61eb60c-9c35-4d20-a928-2b84e02af89c Policy settings Header name Header value CORS headers: Access-Control-Allow- * Origin Override origin? No Security headers: Referrer-Policy strict-origin- No when-cross-or igin Strict-Transport-S ecurity max-age=3 1536000 No CORS-and-SecurityHeadersPolicy 278 Amazon CloudFront Developer Guide Header name Header value X-Content-Type-Options nosniff X-Frame-Options SAMEORIGIN X-XSS-Protection 1; mode=block Override origin? Yes No No CORS-With-Preflight View this policy in the CloudFront console Use this managed policy to allow CORS requests from any origin, including preflight requests. For preflight requests (using the HTTP OPTIONS method), CloudFront adds all three of the following headers to the response. For simple CORS requests, CloudFront adds only the Access-Control- Allow-Origin header. If the response that CloudFront receives from the origin includes any of these headers, CloudFront uses the received header (and its value) in its response to the viewer. CloudFront doesn't use the header in this policy. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 5cc3b908-e619-4b99-88e5-2cf7f45965bd Policy settings Header name Header value CORS headers: Access-Control-Allow- Methods DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT Override origin? No Access-Control-Allow- Origin Access-Control-Expose- Headers * * CORS-With-Preflight 279 Amazon CloudFront Developer Guide CORS-with-preflight-and-SecurityHeadersPolicy View this policy in the CloudFront console Use this managed policy to allow CORS requests from any origin. This includes preflight requests. This policy also adds a set of security headers to all responses that CloudFront sends to viewers. This policy combines the the section called “CORS-With-Preflight” and the section called “SecurityHeadersPolicy” policies into one. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: eaab4381-ed33-4a86-88ca-d9558dc6cd63 Policy settings Header name Header value CORS headers: Access-Control-Allow- Methods DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT Override origin? No Access-Control-Allow- Origin Access-Control-Expose- Headers * * Security headers: Referrer-Policy strict-origin- No when-cross-or igin Strict-Transport-S ecurity max-age=3 1536000 X-Content-Type-Options nosniff X-Frame-Options SAMEORIGIN X-XSS-Protection 1; mode=block No Yes No No CORS-with-preflight-and-SecurityHeadersPolicy 280 Amazon CloudFront SecurityHeadersPolicy View this policy in the CloudFront console Developer Guide Use this managed policy to add a set of security headers to all responses that CloudFront sends to viewers. For more information about these security headers, see Mozilla's web security guidelines. With this response headers policy, CloudFront adds X-Content-Type-Options: nosniff to all responses. This is the case when the response that CloudFront received from the origin included this header and when it didn't. For all other headers in this policy, if the response that CloudFront receives from the origin includes the header, CloudFront uses the received header (and its value) in its response to the viewer. It doesn't use the header in this policy. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 67f7725c-6f97-4210-82d7-5512b31e9d03 Policy settings Security headers: Header name Header value Override origin? Referrer-Policy strict-origin- No when-cross-or igin Strict-Transport-S ecurity max-age=3 1536000 X-Content-Type-Options nosniff X-Frame-Options SAMEORIGIN X-XSS-Protection 1; mode=block No Yes No No SimpleCORS View this policy in the CloudFront console SecurityHeadersPolicy 281 Amazon CloudFront Developer Guide Use this managed policy to allow simple CORS requests from any origin. With this policy, CloudFront adds the header Access-Control-Allow-Origin: * to all responses for simple CORS requests. If the response that CloudFront receives from the origin includes the Access-Control- Allow-Origin header, CloudFront uses that header (and its value) in its response to the viewer. CloudFront doesn't use the header in this policy. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 60669652-455b-4ae9-85a4-c4c02393f86c Policy settings Header name Header value CORS headers: |
AmazonCloudFront_DevGuide-110 | AmazonCloudFront_DevGuide.pdf | 110 | policy in the CloudFront console SecurityHeadersPolicy 281 Amazon CloudFront Developer Guide Use this managed policy to allow simple CORS requests from any origin. With this policy, CloudFront adds the header Access-Control-Allow-Origin: * to all responses for simple CORS requests. If the response that CloudFront receives from the origin includes the Access-Control- Allow-Origin header, CloudFront uses that header (and its value) in its response to the viewer. CloudFront doesn't use the header in this policy. When using AWS CloudFormation, the AWS CLI, or the CloudFront API, the ID for this policy is: 60669652-455b-4ae9-85a4-c4c02393f86c Policy settings Header name Header value CORS headers: Access-Control-Allow- * Origin Override origin? No SimpleCORS 282 Amazon CloudFront Developer Guide Request and response behavior The following topics describe how CloudFront handles requests and responses. You can learn about how CloudFront interacts with Amazon S3 or custom origins, handles various HTTP methods and headers, processes status codes, and manages caching and error responses. Topics • How CloudFront processes HTTP and HTTPS requests • Request and response behavior for Amazon S3 origins • Request and response behavior for custom origins • Request and response behavior for origin groups • Add custom headers to origin requests • How CloudFront processes partial requests for an object (range GETs) • How CloudFront processes HTTP 3xx status codes from your origin • How CloudFront processes HTTP 4xx and 5xx status codes from your origin • Generate custom error responses How CloudFront processes HTTP and HTTPS requests For Amazon S3 origins, CloudFront accepts requests in both HTTP and HTTPS protocols for objects in a CloudFront distribution by default. CloudFront then forwards the requests to your Amazon S3 bucket using the same protocol in which the requests were made. For custom origins, when you create your distribution, you can specify how CloudFront accesses your origin: HTTP only, or matching the protocol that is used by the viewer. For more information about how CloudFront handles HTTP and HTTPS requests for custom origins, see Protocols. For information about how to restrict your distribution so that end users can only access objects using HTTPS, see Use HTTPS with CloudFront. Note The charge for HTTPS requests is higher than the charge for HTTP requests. For more information about billing rates, see CloudFront pricing. How CloudFront processes HTTP and HTTPS requests 283 Amazon CloudFront Developer Guide Request and response behavior for Amazon S3 origins To understand how CloudFront processes requests and responses when you're using Amazon S3 as your origin, see the following sections: Topics • How CloudFront processes and forwards requests to your Amazon S3 origin • How CloudFront processes responses from your Amazon S3 origin How CloudFront processes and forwards requests to your Amazon S3 origin Learn about how CloudFront processes viewer requests and forwards the requests to your Amazon S3 origin. Contents • Caching duration and minimum TTL • Client IP addresses • Conditional GET requests • Cookies • Cross-origin resource sharing (CORS) • GET requests that include a body • HTTP methods • HTTP request headers that CloudFront removes or updates • Maximum length of a request and maximum length of a URL • OCSP stapling • Protocols • Query strings • Origin connection timeout and attempts • Origin response timeout • Simultaneous requests for the same object (request collapsing) Request and response behavior for Amazon S3 origins 284 Amazon CloudFront Developer Guide Caching duration and minimum TTL To control how long your objects stay in a CloudFront cache before CloudFront forwards another request to your origin, you can: • Configure your origin to add a Cache-Control or an Expires header field to each object. • Specify a value for Minimum TTL in CloudFront cache behaviors. • Use the default value of 24 hours. For more information, see Manage how long content stays in the cache (expiration). Client IP addresses If a viewer sends a request to CloudFront and doesn't include an X-Forwarded-For request header, CloudFront gets the IP address of the viewer from the TCP connection, adds an X- Forwarded-For header that includes the IP address, and forwards the request to the origin. For example, if CloudFront gets the IP address 192.0.2.2 from the TCP connection, it forwards the following header to the origin: X-Forwarded-For: 192.0.2.2 If a viewer sends a request to CloudFront and includes an X-Forwarded-For request header, CloudFront gets the IP address of the viewer from the TCP connection, appends it to the end of the X-Forwarded-For header, and forwards the request to the origin. For example, if the viewer request includes X-Forwarded-For: 192.0.2.4,192.0.2.3 and CloudFront gets the IP address 192.0.2.2 from the TCP connection, it forwards the following header to the origin: X-Forwarded-For: 192.0.2.4,192.0.2.3,192.0.2.2 Note The X-Forwarded-For header contains IPv4 addresses (such as 192.0.2.44) and IPv6 addresses (such as 2001:0db8:85a3::8a2e:0370:7334). Conditional GET requests When CloudFront receives a request for an object that |
AmazonCloudFront_DevGuide-111 | AmazonCloudFront_DevGuide.pdf | 111 | If a viewer sends a request to CloudFront and includes an X-Forwarded-For request header, CloudFront gets the IP address of the viewer from the TCP connection, appends it to the end of the X-Forwarded-For header, and forwards the request to the origin. For example, if the viewer request includes X-Forwarded-For: 192.0.2.4,192.0.2.3 and CloudFront gets the IP address 192.0.2.2 from the TCP connection, it forwards the following header to the origin: X-Forwarded-For: 192.0.2.4,192.0.2.3,192.0.2.2 Note The X-Forwarded-For header contains IPv4 addresses (such as 192.0.2.44) and IPv6 addresses (such as 2001:0db8:85a3::8a2e:0370:7334). Conditional GET requests When CloudFront receives a request for an object that has expired from an edge cache, it forwards the request to the Amazon S3 origin to get the latest version of the object or to get confirmation How CloudFront processes and forwards requests to your Amazon S3 origin 285 Amazon CloudFront Developer Guide from Amazon S3 that the CloudFront edge cache already has the latest version. When Amazon S3 originally sent the object to CloudFront, it included an ETag value and a LastModified value in the response. In the new request that CloudFront forwards to Amazon S3, CloudFront adds one or both of the following headers: • An If-Match or If-None-Match header that contains the ETag value for the expired version of the object. • An If-Modified-Since header that contains the LastModified value for the expired version of the object. Amazon S3 uses this information to determine whether the object has been updated and, therefore, whether to return the entire object to CloudFront or to return only an HTTP 304 status code (not modified). Cookies Amazon S3 doesn't process cookies. If you configure a cache behavior to forward cookies to an Amazon S3 origin, CloudFront forwards the cookies, but Amazon S3 ignores them. All future requests for the same object, regardless if you vary the cookie, are served from the existing object in the cache. Cross-origin resource sharing (CORS) If you want CloudFront to respect Amazon S3 cross-origin resource sharing settings, configure CloudFront to forward selected headers to Amazon S3. For more information, see Cache content based on request headers. GET requests that include a body If a viewer GET request includes a body, CloudFront returns an HTTP status code 403 (Forbidden) to the viewer. HTTP methods If you configure CloudFront to process all of the HTTP methods that it supports, CloudFront accepts the following requests from viewers and forwards them to your Amazon S3 origin: • DELETE How CloudFront processes and forwards requests to your Amazon S3 origin 286 Amazon CloudFront • GET • HEAD • OPTIONS • PATCH • POST • PUT Developer Guide CloudFront always caches responses to GET and HEAD requests. You can also configure CloudFront to cache responses to OPTIONS requests. CloudFront doesn't cache responses to requests that use the other methods. If you want to use multi-part uploads to add objects to an Amazon S3 bucket, you must add a CloudFront origin access control (OAC) to your distribution and give the OAC the needed permissions. For more information, see the section called “Restrict access to an Amazon S3 origin”. Important If you configure CloudFront to accept and forward to Amazon S3 all of the HTTP methods that CloudFront supports, you must create a CloudFront OAC to restrict access to your Amazon S3 content and give the OAC the required permissions. For example, if you configure CloudFront to accept and forward these methods because you want to use the PUT method, you must configure Amazon S3 bucket policies to handle DELETE requests appropriately so viewers can't delete resources that you don't want them to. For more information, see the section called “Restrict access to an Amazon S3 origin”. For information about the operations supported by Amazon S3, see the Amazon S3 documentation. HTTP request headers that CloudFront removes or updates CloudFront removes or updates some headers before forwarding requests to your Amazon S3 origin. For most headers this behavior is the same as for custom origins. For a full list of HTTP request headers and how CloudFront processes them, see HTTP request headers and CloudFront behavior (custom and Amazon S3 origins). How CloudFront processes and forwards requests to your Amazon S3 origin 287 Amazon CloudFront Developer Guide Maximum length of a request and maximum length of a URL The maximum length of a request, including the path, the query string (if any), and headers, is 20,480 bytes. CloudFront constructs a URL from the request. The maximum length of this URL is 8192 bytes. If a request or a URL exceeds the maximum length, CloudFront returns the HTTP status code 413 (Request Entity Too Large), to the viewer, and then terminates the TCP connection to the viewer. OCSP stapling When a viewer submits an HTTPS request for an object, CloudFront or the viewer must confirm with |
AmazonCloudFront_DevGuide-112 | AmazonCloudFront_DevGuide.pdf | 112 | Developer Guide Maximum length of a request and maximum length of a URL The maximum length of a request, including the path, the query string (if any), and headers, is 20,480 bytes. CloudFront constructs a URL from the request. The maximum length of this URL is 8192 bytes. If a request or a URL exceeds the maximum length, CloudFront returns the HTTP status code 413 (Request Entity Too Large), to the viewer, and then terminates the TCP connection to the viewer. OCSP stapling When a viewer submits an HTTPS request for an object, CloudFront or the viewer must confirm with the certificate authority (CA) that the SSL certificate for the domain hasn't been revoked. OCSP stapling speeds up certificate validation by allowing CloudFront to validate the certificate and to cache the response from the CA, so the client doesn't need to validate the certificate directly with the CA. The performance improvement of OCSP stapling is more pronounced when CloudFront receives many HTTPS requests for objects in the same domain. Each server in a CloudFront edge location must submit a separate validation request. When CloudFront receives a lot of HTTPS requests for the same domain, every server in the edge location soon has a response from the CA that it can staple to a packet in the SSL handshake. When the viewer is satisfied that the certificate is valid, CloudFront can serve the requested object. If your distribution doesn't get much traffic in a CloudFront edge location, new requests are more likely to be directed to a server that hasn't validated the certificate with the CA yet. In that case, the viewer separately performs the validation step and the CloudFront server serves the object. That CloudFront server also submits a validation request to the CA, so the next time it receives a request that includes the same domain name, it has a validation response from the CA. Protocols CloudFront forwards HTTP or HTTPS requests to the origin server based on the protocol of the viewer request, either HTTP or HTTPS. Important If your Amazon S3 bucket is configured as a website endpoint, you can't configure CloudFront to use HTTPS to communicate with your origin because Amazon S3 doesn't support HTTPS connections in that configuration. How CloudFront processes and forwards requests to your Amazon S3 origin 288 Amazon CloudFront Query strings Developer Guide You can configure whether CloudFront forwards query string parameters to your Amazon S3 origin. For more information, see Cache content based on query string parameters. Origin connection timeout and attempts Origin connection timeout is the number of seconds that CloudFront waits when trying to establish a connection to the origin. Origin connection attempts is the number of times that CloudFront attempts to connect to the origin. Together, these settings determine how long CloudFront tries to connect to the origin before failing over to the secondary origin (in the case of an origin group) or returning an error response to the viewer. By default, CloudFront waits as long as 30 seconds (3 attempts of 10 seconds each) before attempting to connect to the secondary origin or returning an error response. You can reduce this time by specifying a shorter connection timeout, fewer attempts, or both. For more information, see Control origin timeouts and attempts. Origin response timeout The origin response timeout, also known as the origin read timeout or origin request timeout, applies to both of the following: • The amount of time, in seconds, that CloudFront waits for a response after forwarding a request to the origin. • The amount of time, in seconds, that CloudFront waits after receiving a packet of a response from the origin and before receiving the next packet. CloudFront behavior depends on the HTTP method of the viewer request: • GET and HEAD requests – If the origin doesn’t respond within 30 seconds or stops responding for 30 seconds, CloudFront drops the connection. If the specified number of origin connection attempts is more than 1, CloudFront tries again to get a complete response. CloudFront tries up to 3 times, as determined by the value of the origin connection attempts setting. If the origin doesn’t respond during the final attempt, CloudFront doesn’t try again until it receives another request for content on the same origin. How CloudFront processes and forwards requests to your Amazon S3 origin 289 Amazon CloudFront Developer Guide • DELETE, OPTIONS, PATCH, PUT, and POST requests – If the origin doesn’t respond within 30 seconds, CloudFront drops the connection and doesn’t try again to contact the origin. The client can resubmit the request if necessary. You can’t change the response timeout for an Amazon S3 origin (an S3 bucket that is not configured with static website hosting). Simultaneous requests for the same object (request collapsing) When a CloudFront edge location receives a |
AmazonCloudFront_DevGuide-113 | AmazonCloudFront_DevGuide.pdf | 113 | it receives another request for content on the same origin. How CloudFront processes and forwards requests to your Amazon S3 origin 289 Amazon CloudFront Developer Guide • DELETE, OPTIONS, PATCH, PUT, and POST requests – If the origin doesn’t respond within 30 seconds, CloudFront drops the connection and doesn’t try again to contact the origin. The client can resubmit the request if necessary. You can’t change the response timeout for an Amazon S3 origin (an S3 bucket that is not configured with static website hosting). Simultaneous requests for the same object (request collapsing) When a CloudFront edge location receives a request for an object and the object isn't in the cache or the cached object is expired, CloudFront immediately sends the request to the origin. However, if there are simultaneous requests for the same object—that is, if additional requests for the same object (with the same cache key) arrive at the edge location before CloudFront receives the response to the first request—CloudFront pauses before forwarding the additional requests to the origin. This brief pause helps to reduce the load on the origin. CloudFront sends the response from the original request to all the requests that it received while it was paused. This is called request collapsing. In CloudFront logs, the first request is identified as a Miss in the x-edge- result-type field, and the collapsed requests are identified as a Hit. For more information about CloudFront logs, see the section called “CloudFront and edge function logging”. CloudFront only collapses requests that share a cache key. If the additional requests do not share the same cache key because, for example, you configured CloudFront to cache based on request headers or cookies or query strings, CloudFront forwards all the requests with a unique cache key to your origin. If you want to prevent all request collapsing, you can use the managed cache policy CachingDisabled, which also prevents caching. For more information, see Use managed cache policies. If you want to prevent request collapsing for specific objects, you can set the minimum TTL for the cache behavior to 0 and configure the origin to send Cache-Control: private, Cache- Control: no-store, Cache-Control: no-cache, Cache-Control: max-age=0, or Cache- Control: s-maxage=0. These configurations will increase the load on your origin and introduce additional latency for the simultaneous requests that are paused while CloudFront waits for the response to the first request. How CloudFront processes and forwards requests to your Amazon S3 origin 290 Amazon CloudFront Important Developer Guide Currently, CloudFront doesn't support request collapsing if you enable cookie forwarding in the cache policy, the origin request policy, or the legacy cache settings. How CloudFront processes responses from your Amazon S3 origin Learn about how CloudFront processes responses from your Amazon S3 origin. Contents • Canceled requests • HTTP response headers that CloudFront removes or updates • Maximum cacheable file size • Redirects Canceled requests If an object is not in the edge cache, and if a viewer terminates a session (for example, closes a browser) after CloudFront gets the object from your origin but before it can deliver the requested object, CloudFront does not cache the object in the edge location. HTTP response headers that CloudFront removes or updates CloudFront removes or updates the following header fields before forwarding the response from your Amazon S3 origin to the viewer: • X-Amz-Id-2 • X-Amz-Request-Id • Set-Cookie – If you configure CloudFront to forward cookies, it will forward the Set-Cookie header field to clients. For more information, see Cache content based on cookies. • Trailer • Transfer-Encoding – If your Amazon S3 origin returns this header field, CloudFront sets the value to chunked before returning the response to the viewer. • Upgrade How CloudFront processes responses from your Amazon S3 origin 291 Amazon CloudFront Developer Guide • Via – CloudFront sets the value to the following in the response to the viewer: Via: http-version alphanumeric-string.cloudfront.net (CloudFront) For example, the value is something like the following: Via: 1.1 1026589cc7887e7a0dc7827b4example.cloudfront.net (CloudFront) Maximum cacheable file size The maximum size of a response body that CloudFront saves in its cache is 50 GB. This includes chunked transfer responses that don't specify the Content-Length header value. You can use CloudFront to cache an object that is larger than this size by using range requests to request the objects in parts that are each 50 GB or smaller. CloudFront caches these parts because each of them is 50 GB or smaller. After the viewer retrieves all the parts of the object, it can reconstruct the original, larger object. For more information, see Use range requests to cache large objects. Redirects You can configure an Amazon S3 bucket to redirect all requests to another host name; this can be another Amazon S3 bucket or an HTTP server. If you configure a bucket to redirect all |
AmazonCloudFront_DevGuide-114 | AmazonCloudFront_DevGuide.pdf | 114 | object that is larger than this size by using range requests to request the objects in parts that are each 50 GB or smaller. CloudFront caches these parts because each of them is 50 GB or smaller. After the viewer retrieves all the parts of the object, it can reconstruct the original, larger object. For more information, see Use range requests to cache large objects. Redirects You can configure an Amazon S3 bucket to redirect all requests to another host name; this can be another Amazon S3 bucket or an HTTP server. If you configure a bucket to redirect all requests and if the bucket is the origin for a CloudFront distribution, we recommend that you configure the bucket to redirect all requests to a CloudFront distribution using either the domain name for the distribution (for example, d111111abcdef8.cloudfront.net) or an alternate domain name (a CNAME) that is associated with a distribution (for example, example.com). Otherwise, viewer requests bypass CloudFront, and the objects are served directly from the new origin. Note If you redirect requests to an alternate domain name, you must also update the DNS service for your domain by adding a CNAME record. For more information, see Use custom URLs by adding alternate domain names (CNAMEs). Here's what happens when you configure a bucket to redirect all requests: 1. A viewer (for example, a browser) requests an object from CloudFront. How CloudFront processes responses from your Amazon S3 origin 292 Amazon CloudFront Developer Guide 2. CloudFront forwards the request to the Amazon S3 bucket that is the origin for your distribution. 3. Amazon S3 returns an HTTP status code 301 (Moved Permanently) as well as the new location. 4. CloudFront caches the redirect status code and the new location, and returns the values to the viewer. CloudFront does not follow the redirect to get the object from the new location. 5. The viewer sends another request for the object, but this time the viewer specifies the new location that it got from CloudFront: • If the Amazon S3 bucket is redirecting all requests to a CloudFront distribution, using either the domain name for the distribution or an alternate domain name, CloudFront requests the object from the Amazon S3 bucket or the HTTP server in the new location. When the new location returns the object, CloudFront returns it to the viewer and caches it in an edge location. • If the Amazon S3 bucket is redirecting requests to another location, the second request bypasses CloudFront. The Amazon S3 bucket or the HTTP server in the new location returns the object directly to the viewer, so the object is never cached in a CloudFront edge cache. Request and response behavior for custom origins To understand how CloudFront processes requests and responses when you're using custom origins, see the following sections: Topics • How CloudFront processes and forwards requests to your custom origin • How CloudFront processes responses from your custom origin How CloudFront processes and forwards requests to your custom origin Learn about how CloudFront processes viewer requests and forwards the requests to your custom origin. Contents • Authentication • Caching duration and minimum TTL • Client IP addresses Request and response behavior for custom origins 293 Developer Guide Amazon CloudFront • Client-side SSL authentication • Compression • Conditional requests • Cookies • Cross-origin resource sharing (CORS) • Encryption • GET requests that include a body • HTTP methods • HTTP request headers and CloudFront behavior (custom and Amazon S3 origins) • HTTP version • Maximum length of a request and maximum length of a URL • OCSP stapling • Persistent connections • Protocols • Query strings • Origin connection timeout and attempts • Origin response timeout • Simultaneous requests for the same object (request collapsing) • User-Agent header Authentication If you forward the Authorization header to your origin, you can then configure your origin server to request client authentication for the following types of requests: • DELETE • GET • HEAD • PATCH • PUT • POST How CloudFront processes and forwards requests to your custom origin 294 Amazon CloudFront Developer Guide For OPTIONS requests, client authentication can only be configured if you use the following CloudFront settings: • CloudFront is configured to forward the Authorization header to your origin • CloudFront is configured to not cache the response to OPTIONS requests For more information, see Configure CloudFront to forward the Authorization header. You can use HTTP or HTTPS to forward requests to your origin server. For more information, see Use HTTPS with CloudFront. Caching duration and minimum TTL To control how long your objects stay in a CloudFront cache before CloudFront forwards another request to your origin, you can: • Configure your origin to add a Cache-Control or an Expires header field to each object. • Specify a value |
AmazonCloudFront_DevGuide-115 | AmazonCloudFront_DevGuide.pdf | 115 | is configured to forward the Authorization header to your origin • CloudFront is configured to not cache the response to OPTIONS requests For more information, see Configure CloudFront to forward the Authorization header. You can use HTTP or HTTPS to forward requests to your origin server. For more information, see Use HTTPS with CloudFront. Caching duration and minimum TTL To control how long your objects stay in a CloudFront cache before CloudFront forwards another request to your origin, you can: • Configure your origin to add a Cache-Control or an Expires header field to each object. • Specify a value for Minimum TTL in CloudFront cache behaviors. • Use the default value of 24 hours. For more information, see Manage how long content stays in the cache (expiration). Client IP addresses If a viewer sends a request to CloudFront and does not include an X-Forwarded-For request header, CloudFront gets the IP address of the viewer from the TCP connection, adds an X- Forwarded-For header that includes the IP address, and forwards the request to the origin. For example, if CloudFront gets the IP address 192.0.2.2 from the TCP connection, it forwards the following header to the origin: X-Forwarded-For: 192.0.2.2 If a viewer sends a request to CloudFront and includes an X-Forwarded-For request header, CloudFront gets the IP address of the viewer from the TCP connection, appends it to the end of the X-Forwarded-For header, and forwards the request to the origin. For example, if the viewer request includes X-Forwarded-For: 192.0.2.4,192.0.2.3 and CloudFront gets the IP address 192.0.2.2 from the TCP connection, it forwards the following header to the origin: How CloudFront processes and forwards requests to your custom origin 295 Amazon CloudFront Developer Guide X-Forwarded-For: 192.0.2.4,192.0.2.3,192.0.2.2 Some applications, such as load balancers (including Elastic Load Balancing), web application firewalls, reverse proxies, intrusion prevention systems, and API Gateway, append the IP address of the CloudFront edge server that forwarded the request onto the end of the X-Forwarded-For header. For example, if CloudFront includes X-Forwarded-For: 192.0.2.2 in a request that it forwards to ELB and if the IP address of the CloudFront edge server is 192.0.2.199, the request that your EC2 instance receives contains the following header: X-Forwarded-For: 192.0.2.2,192.0.2.199 Note The X-Forwarded-For header contains IPv4 addresses (such as 192.0.2.44) and IPv6 addresses (such as 2001:0db8:85a3::8a2e:0370:7334). Also note that the X-Forwarded-For header may be modified by every node on the path to the current server (CloudFront). For more information, see section 8.1 in RFC 7239. You can also modify the header using CloudFront edge compute functions. Client-side SSL authentication CloudFront does not support client authentication with client-side SSL certificates. If an origin requests a client-side certificate, CloudFront drops the request. Compression For more information, see Serve compressed files. Conditional requests When CloudFront receives a request for an object that has expired from an edge cache, it forwards the request to the origin either to get the latest version of the object or to get confirmation from the origin that the CloudFront edge cache already has the latest version. Typically, when the origin last sent the object to CloudFront, it included an ETag value, a LastModified value, or both values in the response. In the new request that CloudFront forwards to the origin, CloudFront adds one or both of the following: • An If-Match or If-None-Match header that contains the ETag value for the expired version of the object. How CloudFront processes and forwards requests to your custom origin 296 Amazon CloudFront Developer Guide • An If-Modified-Since header that contains the LastModified value for the expired version of the object. The origin uses this information to determine whether the object has been updated and, therefore, whether to return the entire object to CloudFront or to return only an HTTP 304 status code (not modified). Note If-Modified-Since and If-None-Match conditional requests are not supported when CloudFront is configured to forward cookies (all or a subset). For more information, see Cache content based on cookies. Cookies You can configure CloudFront to forward cookies to your origin. For more information, see Cache content based on cookies. Cross-origin resource sharing (CORS) If you want CloudFront to respect cross-origin resource sharing settings, configure CloudFront to forward the Origin header to your origin. For more information, see Cache content based on request headers. Encryption You can require viewers to use HTTPS to send requests to CloudFront and require CloudFront to forward requests to your custom origin by using the protocol that is used by the viewer. For more information, see the following distribution settings: • Viewer protocol policy • Protocol (custom origins only) CloudFront forwards HTTPS requests to the origin server using the SSLv3, TLSv1.0, TLSv1.1, and TLSv1.2 protocols. For custom origins, you can choose the SSL protocols that you want CloudFront to use when communicating with your origin: How |
AmazonCloudFront_DevGuide-116 | AmazonCloudFront_DevGuide.pdf | 116 | to your origin. For more information, see Cache content based on request headers. Encryption You can require viewers to use HTTPS to send requests to CloudFront and require CloudFront to forward requests to your custom origin by using the protocol that is used by the viewer. For more information, see the following distribution settings: • Viewer protocol policy • Protocol (custom origins only) CloudFront forwards HTTPS requests to the origin server using the SSLv3, TLSv1.0, TLSv1.1, and TLSv1.2 protocols. For custom origins, you can choose the SSL protocols that you want CloudFront to use when communicating with your origin: How CloudFront processes and forwards requests to your custom origin 297 Amazon CloudFront Developer Guide • If you're using the CloudFront console, choose protocols by using the Origin SSL Protocols check boxes. For more information, see Create a distribution. • If you're using the CloudFront API, specify protocols by using the OriginSslProtocols element. For more information, see OriginSslProtocols and DistributionConfig in the Amazon CloudFront API Reference. If the origin is an Amazon S3 bucket, CloudFront always uses TLSv1.2. Important Other versions of SSL and TLS are not supported. For more information about using HTTPS with CloudFront, see Use HTTPS with CloudFront. For lists of the ciphers that CloudFront supports for HTTPS communication between viewers and CloudFront, and between CloudFront and your origin, see Supported protocols and ciphers between viewers and CloudFront. GET requests that include a body If a viewer GET request includes a body, CloudFront returns an HTTP status code 403 (Forbidden) to the viewer. HTTP methods If you configure CloudFront to process all of the HTTP methods that it supports, CloudFront accepts the following requests from viewers and forwards them to your custom origin: • DELETE • GET • HEAD • OPTIONS • PATCH • POST • PUT How CloudFront processes and forwards requests to your custom origin 298 Amazon CloudFront Developer Guide CloudFront always caches responses to GET and HEAD requests. You can also configure CloudFront to cache responses to OPTIONS requests. CloudFront does not cache responses to requests that use the other methods. For information about configuring whether your custom origin processes these methods, see the documentation for your origin. Important If you configure CloudFront to accept and forward to your origin all of the HTTP methods that CloudFront supports, configure your origin server to handle all methods. For example, if you configure CloudFront to accept and forward these methods because you want to use POST, you must configure your origin server to handle DELETE requests appropriately so viewers can't delete resources that you don't want them to. For more information, see the documentation for your HTTP server. HTTP request headers and CloudFront behavior (custom and Amazon S3 origins) The following table lists HTTP request headers that you can forward to both custom and Amazon S3 origins (with the exceptions that are noted). For each header, the table includes information about the following: • CloudFront behavior if you don't configure CloudFront to forward the header to your origin, which causes CloudFront to cache your objects based on header values. • Whether you can configure CloudFront to cache objects based on header values for that header. You can configure CloudFront to cache objects based on values in the Date and User-Agent headers, but we don't recommend it. These headers have many possible values, and caching based on their values would cause CloudFront to forward significantly more requests to your origin. For more information about caching based on header values, see Cache content based on request headers. How CloudFront processes and forwards requests to your custom origin 299 Amazon CloudFront Header Behavior if you don't configure CloudFront to cache based on header values Developer Guide Caching based on header values is supported Other-defined headers Legacy cache settings – CloudFront forwards the headers to your origin. Yes Yes Yes Yes Yes Yes Accept CloudFront removes the header. Accept-Charset CloudFront removes the header. Accept-Encoding If the value contains gzip or br, CloudFront forwards a normalized Accept-Encoding header to your origin. For more information, see Compression support and Serve compressed files. Accept-Language CloudFront removes the header. Authorization • • GET and HEAD requests – CloudFront removes the Authorization header field before forwarding the request to your origin. OPTIONS requests – CloudFront removes the Authorization header field before forwarding the request to your origin if you configure CloudFront to cache responses to OPTIONS requests. CloudFront forwards the Authorization header field to your origin if you do not How CloudFront processes and forwards requests to your custom origin 300 Amazon CloudFront Header Behavior if you don't configure CloudFront to cache based on header values Developer Guide Caching based on header values is supported configure CloudFront to cache responses to OPTIONS requests. • DELETE, PATCH, POST, and PUT requests – CloudFront does not remove the |
AmazonCloudFront_DevGuide-117 | AmazonCloudFront_DevGuide.pdf | 117 | the request to your origin. OPTIONS requests – CloudFront removes the Authorization header field before forwarding the request to your origin if you configure CloudFront to cache responses to OPTIONS requests. CloudFront forwards the Authorization header field to your origin if you do not How CloudFront processes and forwards requests to your custom origin 300 Amazon CloudFront Header Behavior if you don't configure CloudFront to cache based on header values Developer Guide Caching based on header values is supported configure CloudFront to cache responses to OPTIONS requests. • DELETE, PATCH, POST, and PUT requests – CloudFront does not remove the header field before forwarding the request to your origin. Cache-Control CloudFront forwards the header to your origin. No CloudFront-Forward ed-Proto CloudFront does not add the header before forwarding the request to your origin. For more information, see Configure caching based on the protocol of the request. CloudFront-Is-Desk top-Viewer CloudFront does not add the header before forwarding the request to your origin. For more information, see Configure caching based on the device type. CloudFront-Is-Mobi le-Viewer CloudFront does not add the header before forwarding the request to your origin. For more information, see Configure caching based on the device type. Yes Yes Yes How CloudFront processes and forwards requests to your custom origin 301 Amazon CloudFront Header Behavior if you don't configure CloudFront to cache based on header values CloudFront-Is-Tabl et-Viewer CloudFront does not add the header before forwarding the request to your origin. For more information, see Configure caching based on the device type. CloudFront-Viewer- Country CloudFront does not add the header before forwarding the request to your origin. Developer Guide Caching based on header values is supported Yes Yes Connection CloudFront replaces this header with Connectio No n: Keep-Alive request to your origin. before forwarding the Content-Length CloudFront forwards the header to your origin. No Content-MD5 CloudFront forwards the header to your origin. Yes Content-Type CloudFront forwards the header to your origin. Yes Cookie If you configure CloudFront to forward cookies, No it will forward the Cookie header field to your origin. If you don't, CloudFront removes the Cookie header field. For more information, see Cache content based on cookies. How CloudFront processes and forwards requests to your custom origin 302 Amazon CloudFront Header Behavior if you don't configure CloudFront to cache based on header values Date CloudFront forwards the header to your origin. Expect CloudFront removes the header. Developer Guide Caching based on header values is supported Yes, but not recommend ed Yes From Host CloudFront forwards the header to your origin. Yes CloudFront sets the value to the domain name of the origin that is associated with the requested Yes (custom) object. You can't cache based on the Host header for Amazon S3 or MediaStore origins. No (S3 and MediaStore) If-Match CloudFront forwards the header to your origin. Yes If-Modified-Since CloudFront forwards the header to your origin. Yes If-None-Match CloudFront forwards the header to your origin. Yes If-Range CloudFront forwards the header to your origin. Yes If-Unmodified-Sinc CloudFront forwards the header to your origin. Yes e How CloudFront processes and forwards requests to your custom origin 303 Amazon CloudFront Header Behavior if you don't configure CloudFront to cache based on header values Developer Guide Caching based on header values is supported Max-Forwards CloudFront forwards the header to your origin. No Origin Pragma CloudFront forwards the header to your origin. Yes CloudFront forwards the header to your origin. No Proxy-Authenticate CloudFront removes the header. Proxy-Authorizatio CloudFront removes the header. n Proxy-Connection CloudFront removes the header. No No No Range CloudFront forwards the header to your origin. For more information, see How CloudFront processes Yes, by default partial requests for an object (range GETs). Referer CloudFront removes the header. Yes Request-Range CloudFront forwards the header to your origin. No TE CloudFront removes the header. Trailer CloudFront removes the header. No No How CloudFront processes and forwards requests to your custom origin 304 Amazon CloudFront Header Behavior if you don't configure CloudFront to cache based on header values Developer Guide Caching based on header values is supported Transfer-Encoding CloudFront forwards the header to your origin. No Upgrade CloudFront removes the header, unless you've established a WebSocket connection. User-Agent CloudFront replaces the value of this header field with Amazon CloudFront . If you want CloudFront to cache your content based on the device the user is using, see Configure caching based on the device type. No (except for WebSocket connectio ns) Yes, but not recommend ed Via CloudFront forwards the header to your origin. Yes Warning CloudFront forwards the header to your origin. Yes X-Amz-Cf-Id CloudFront adds the header to the viewer request before forwarding the request to your origin. The header value contains an encrypted string that uniquely identifies the request. X-Edge-* CloudFront removes all X-Edge-* headers. X-Forwarded-For CloudFront forwards the |
AmazonCloudFront_DevGuide-118 | AmazonCloudFront_DevGuide.pdf | 118 | value of this header field with Amazon CloudFront . If you want CloudFront to cache your content based on the device the user is using, see Configure caching based on the device type. No (except for WebSocket connectio ns) Yes, but not recommend ed Via CloudFront forwards the header to your origin. Yes Warning CloudFront forwards the header to your origin. Yes X-Amz-Cf-Id CloudFront adds the header to the viewer request before forwarding the request to your origin. The header value contains an encrypted string that uniquely identifies the request. X-Edge-* CloudFront removes all X-Edge-* headers. X-Forwarded-For CloudFront forwards the header to your origin. For more information, see Client IP addresses. No No Yes How CloudFront processes and forwards requests to your custom origin 305 Amazon CloudFront Header Behavior if you don't configure CloudFront to cache based on header values X-Forwarded-Proto CloudFront removes the header. X-HTTP-Method-Over CloudFront removes the header. ride X-Real-IP CloudFront removes the header. Developer Guide Caching based on header values is supported No Yes No HTTP version CloudFront forwards requests to your custom origin using HTTP/1.1. Maximum length of a request and maximum length of a URL The maximum length of a request, including the path, the query string (if any), and headers, is 20,480 bytes. CloudFront constructs a URL from the request. The maximum length of this URL is 8192 bytes. If a request or a URL exceeds these maximums, CloudFront returns HTTP status code 413, Request Entity Too Large, to the viewer, and then terminates the TCP connection to the viewer. OCSP stapling When a viewer submits an HTTPS request for an object, either CloudFront or the viewer must confirm with the certificate authority (CA) that the SSL certificate for the domain has not been revoked. OCSP stapling speeds up certificate validation by allowing CloudFront to validate the certificate and to cache the response from the CA, so the client doesn't need to validate the certificate directly with the CA. The performance improvement of OCSP stapling is more pronounced when CloudFront receives numerous HTTPS requests for objects in the same domain. Each server in a CloudFront edge How CloudFront processes and forwards requests to your custom origin 306 Amazon CloudFront Developer Guide location must submit a separate validation request. When CloudFront receives a lot of HTTPS requests for the same domain, every server in the edge location soon has a response from the CA that it can "staple" to a packet in the SSL handshake; when the viewer is satisfied that the certificate is valid, CloudFront can serve the requested object. If your distribution doesn't get much traffic in a CloudFront edge location, new requests are more likely to be directed to a server that hasn't validated the certificate with the CA yet. In that case, the viewer separately performs the validation step and the CloudFront server serves the object. That CloudFront server also submits a validation request to the CA, so the next time it receives a request that includes the same domain name, it has a validation response from the CA. Persistent connections When CloudFront gets a response from your origin, it tries to maintain the connection for several seconds in case another request arrives during that period. Maintaining a persistent connection saves the time required to re-establish the TCP connection and perform another TLS handshake for subsequent requests. For more information, including how to configure the duration of persistent connections, see Keep- alive timeout (custom and VPC origins only) in the section Distribution settings reference. Protocols CloudFront forwards HTTP or HTTPS requests to the origin server based on the following: • The protocol of the request that the viewer sends to CloudFront, either HTTP or HTTPS. • The value of the Origin Protocol Policy field in the CloudFront console or, if you're using the CloudFront API, the OriginProtocolPolicy element in the DistributionConfig complex type. In the CloudFront console, the options are HTTP Only, HTTPS Only, and Match Viewer. If you specify HTTP Only or HTTPS Only, CloudFront forwards requests to the origin server using the specified protocol, regardless of the protocol in the viewer request. If you specify Match Viewer, CloudFront forwards requests to the origin server using the protocol in the viewer request. Note that CloudFront caches the object only once even if viewers make requests using both HTTP and HTTPS protocols. How CloudFront processes and forwards requests to your custom origin 307 Amazon CloudFront Important Developer Guide If CloudFront forwards a request to the origin using the HTTPS protocol, and if the origin server returns an invalid certificate or a self-signed certificate, CloudFront drops the TCP connection. For information about how to update a distribution using the CloudFront console, see Update a distribution. For information about how to update a distribution using the CloudFront API, go to UpdateDistribution in the |
AmazonCloudFront_DevGuide-119 | AmazonCloudFront_DevGuide.pdf | 119 | viewer request. Note that CloudFront caches the object only once even if viewers make requests using both HTTP and HTTPS protocols. How CloudFront processes and forwards requests to your custom origin 307 Amazon CloudFront Important Developer Guide If CloudFront forwards a request to the origin using the HTTPS protocol, and if the origin server returns an invalid certificate or a self-signed certificate, CloudFront drops the TCP connection. For information about how to update a distribution using the CloudFront console, see Update a distribution. For information about how to update a distribution using the CloudFront API, go to UpdateDistribution in the Amazon CloudFront API Reference. Query strings You can configure whether CloudFront forwards query string parameters to your origin. For more information, see Cache content based on query string parameters. Origin connection timeout and attempts Origin connection timeout is the number of seconds that CloudFront waits when trying to establish a connection to the origin. Origin connection attempts is the number of times that CloudFront attempts to connect to the origin. Together, these settings determine how long CloudFront tries to connect to the origin before failing over to the secondary origin (in the case of an origin group) or returning an error response to the viewer. By default, CloudFront waits as long as 30 seconds (3 attempts of 10 seconds each) before attempting to connect to the secondary origin or returning an error response. You can reduce this time by specifying a shorter connection timeout, fewer attempts, or both. For more information, see Control origin timeouts and attempts. Origin response timeout The origin response timeout, also known as the origin read timeout or origin request timeout, applies to both of the following: • The amount of time, in seconds, that CloudFront waits for a response after forwarding a request to the origin. How CloudFront processes and forwards requests to your custom origin 308 Amazon CloudFront Developer Guide • The amount of time, in seconds, that CloudFront waits after receiving a packet of a response from the origin and before receiving the next packet. CloudFront behavior depends on the HTTP method of the viewer request: • GET and HEAD requests – If the origin doesn’t respond or stops responding within the duration of the response timeout, CloudFront drops the connection. If the specified number of origin connection attempts is more than 1, CloudFront tries again to get a complete response. CloudFront tries up to 3 times, as determined by the value of the origin connection attempts setting. If the origin doesn’t respond during the final attempt, CloudFront doesn’t try again until it receives another request for content on the same origin. • DELETE, OPTIONS, PATCH, PUT, and POST requests – If the origin doesn’t respond for the duration of the read timeout, CloudFront drops the connection and doesn’t try again to contact the origin. The client can resubmit the request if necessary. For more information, including how to configure the origin response timeout, see Response timeout (custom and VPC origins only). Simultaneous requests for the same object (request collapsing) When a CloudFront edge location receives a request for an object and the object isn't in the cache or the cached object is expired, CloudFront immediately sends the request to the origin. However, if there are simultaneous requests for the same object—that is, if additional requests for the same object (with the same cache key) arrive at the edge location before CloudFront receives the response to the first request—CloudFront pauses before forwarding the additional requests to the origin. This brief pause helps to reduce the load on the origin. CloudFront sends the response from the original request to all the requests that it received while it was paused. This is called request collapsing. In CloudFront logs, the first request is identified as a Miss in the x-edge- result-type field, and the collapsed requests are identified as a Hit. For more information about CloudFront logs, see the section called “CloudFront and edge function logging”. CloudFront only collapses requests that share a cache key. If the additional requests do not share the same cache key because, for example, you configured CloudFront to cache based on request headers or cookies or query strings, CloudFront forwards all the requests with a unique cache key to your origin. How CloudFront processes and forwards requests to your custom origin 309 Amazon CloudFront Developer Guide If you want to prevent all request collapsing, you can use the managed cache policy CachingDisabled, which also prevents caching. For more information, see Use managed cache policies. If you want to prevent request collapsing for specific objects, you can set the minimum TTL for the cache behavior to 0 and configure the origin to send Cache-Control: private, Cache- Control: no-store, Cache-Control: no-cache, Cache-Control: max-age=0, or Cache- Control: s-maxage=0. These configurations will increase the load |
AmazonCloudFront_DevGuide-120 | AmazonCloudFront_DevGuide.pdf | 120 | the requests with a unique cache key to your origin. How CloudFront processes and forwards requests to your custom origin 309 Amazon CloudFront Developer Guide If you want to prevent all request collapsing, you can use the managed cache policy CachingDisabled, which also prevents caching. For more information, see Use managed cache policies. If you want to prevent request collapsing for specific objects, you can set the minimum TTL for the cache behavior to 0 and configure the origin to send Cache-Control: private, Cache- Control: no-store, Cache-Control: no-cache, Cache-Control: max-age=0, or Cache- Control: s-maxage=0. These configurations will increase the load on your origin and introduce additional latency for the simultaneous requests that are paused while CloudFront waits for the response to the first request. Important Currently, CloudFront doesn't support request collapsing if you enable cookie forwarding in the cache policy, the origin request policy, or the legacy cache settings. User-Agent header If you want CloudFront to cache different versions of your objects based on the device that a user is using to view your content, we recommend that you configure CloudFront to forward one or more of the following headers to your custom origin: • CloudFront-Is-Desktop-Viewer • CloudFront-Is-Mobile-Viewer • CloudFront-Is-SmartTV-Viewer • CloudFront-Is-Tablet-Viewer Based on the value of the User-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. For example, for some tablet devices, CloudFront might set both CloudFront-Is-Mobile-Viewer and CloudFront-Is-Tablet-Viewer to true. For more information about configuring CloudFront to cache based on request headers, see Cache content based on request headers. You can configure CloudFront to cache objects based on values in the User-Agent header, but we don't recommend it. The User-Agent header has many possible values, and caching based on those values would cause CloudFront to forward significantly more requests to your origin. How CloudFront processes and forwards requests to your custom origin 310 Amazon CloudFront Developer Guide If you do not configure CloudFront to cache objects based on values in the User-Agent header, CloudFront adds a User-Agent header with the following value before it forwards a request to your origin: User-Agent = Amazon CloudFront CloudFront adds this header regardless of whether the request from the viewer includes a User- Agent header. If the request from the viewer includes a User-Agent header, CloudFront removes it. How CloudFront processes responses from your custom origin Learn how CloudFront processes responses from your custom origin. Contents • 100 Continue responses • Caching • Canceled requests • Content negotiation • Cookies • Dropped TCP connections • HTTP response headers that CloudFront removes or replaces • Maximum cacheable file size • Origin unavailable • Redirects • Transfer-Encoding header 100 Continue responses Your origin cannot send more than one 100-Continue response to CloudFront. After the first 100- Continue response, CloudFront expects an HTTP 200 OK response. If your origin sends another 100-Continue response after the first one, CloudFront will return an error. Caching • Ensure that the origin server sets valid and accurate values for the Date and Last-Modified header fields. How CloudFront processes responses from your custom origin 311 Amazon CloudFront Developer Guide • CloudFront normally respects a Cache-Control: no-cache header in the response from the origin. For an exception, see Simultaneous requests for the same object (request collapsing). Canceled requests If an object is not in the edge cache, and if a viewer terminates a session (for example, closes a browser) after CloudFront gets the object from your origin but before it can deliver the requested object, CloudFront does not cache the object in the edge location. Content negotiation If your origin returns Vary:* in the response, and if the value of Minimum TTL for the corresponding cache behavior is 0, CloudFront caches the object but still forwards every subsequent request for the object to the origin to confirm that the cache contains the latest version of the object. CloudFront doesn't include any conditional headers, such as If-None-Match or If-Modified-Since. As a result, your origin returns the object to CloudFront in response to every request. If your origin returns Vary:* in the response, and if the value of Minimum TTL for the corresponding cache behavior is any other value, CloudFront processes the Vary header as described in HTTP response headers that CloudFront removes or replaces. Cookies If you enable cookies for a cache behavior, and if the origin returns cookies with an object, CloudFront caches both the object and the cookies. Note that this reduces cacheability for an object. For more information, see Cache content based on cookies. Dropped TCP connections If the TCP connection between CloudFront and your origin drops while your origin is returning an object to CloudFront, CloudFront behavior depends on whether your |
AmazonCloudFront_DevGuide-121 | AmazonCloudFront_DevGuide.pdf | 121 | value of Minimum TTL for the corresponding cache behavior is any other value, CloudFront processes the Vary header as described in HTTP response headers that CloudFront removes or replaces. Cookies If you enable cookies for a cache behavior, and if the origin returns cookies with an object, CloudFront caches both the object and the cookies. Note that this reduces cacheability for an object. For more information, see Cache content based on cookies. Dropped TCP connections If the TCP connection between CloudFront and your origin drops while your origin is returning an object to CloudFront, CloudFront behavior depends on whether your origin included a Content- Length header in the response: • Content-Length header – CloudFront returns the object to the viewer as it gets the object from your origin. However, if the value of the Content-Length header doesn't match the size of the object, CloudFront doesn't cache the object. How CloudFront processes responses from your custom origin 312 Amazon CloudFront Developer Guide • Transfer-Encoding: Chunked – CloudFront returns the object to the viewer as it gets the object from your origin. However, if the chunked response is not complete, CloudFront does not cache the object. • No Content-Length header – CloudFront returns the object to the viewer and caches it, but the object may not be complete. Without a Content-Length header, CloudFront cannot determine whether the TCP connection was dropped accidentally or on purpose. We recommend that you configure your HTTP server to add a Content-Length header to prevent CloudFront from caching partial objects. HTTP response headers that CloudFront removes or replaces CloudFront removes or updates the following header fields before forwarding the response from your origin to the viewer: • Set-Cookie – If you configure CloudFront to forward cookies, it will forward the Set-Cookie header field to clients. For more information, see Cache content based on cookies. • Trailer • Transfer-Encoding – If your origin returns this header field, CloudFront sets the value to chunked before returning the response to the viewer. • Upgrade • Vary – Note the following: • If you configure CloudFront to forward any of the device-specific headers to your origin (CloudFront-Is-Desktop-Viewer, CloudFront-Is-Mobile-Viewer, CloudFront- Is-SmartTV-Viewer, CloudFront-Is-Tablet-Viewer) and you configure your origin to return Vary:User-Agent to CloudFront, CloudFront returns Vary:User-Agent to the viewer. For more information, see Configure caching based on the device type. • If you configure your origin to include either Accept-Encoding or Cookie in the Vary header, CloudFront includes the values in the response to the viewer. • If you configure CloudFront to forward headers to your origin, and if you configure your origin to return the header names to CloudFront in the Vary header (for example, Vary:Accept- Charset,Accept-Language), CloudFront returns the Vary header with those values to the viewer. • For information about how CloudFront processes a value of * in the Vary header, see Content negotiation. How CloudFront processes responses from your custom origin 313 Amazon CloudFront Developer Guide • If you configure your origin to include any other values in the Vary header, CloudFront removes the values before returning the response to the viewer. • Via – CloudFront sets the value to the following in the response to the viewer: Via: http-version alphanumeric-string.cloudfront.net (CloudFront) For example, the value is something like the following: Via: 1.1 1026589cc7887e7a0dc7827b4example.cloudfront.net (CloudFront) Maximum cacheable file size The maximum size of a response body that CloudFront saves in its cache is 50 GB. This includes chunked transfer responses that don't specify the Content-Length header value. You can use CloudFront to cache an object that is larger than this size by using range requests to request the objects in parts that are each 50 GB or smaller. CloudFront caches these parts because each of them is 50 GB or smaller. After the viewer retrieves all the parts of the object, it can reconstruct the original, larger object. For more information, see Use range requests to cache large objects. Origin unavailable If your origin server is unavailable and CloudFront gets a request for an object that is in the edge cache but that has expired (for example, because the period of time specified in the Cache- Control max-age directive has passed), CloudFront either serves the expired version of the object or serves a custom error page. For more information about CloudFront behavior when you've configured custom error pages, see How CloudFront processes errors when you have configured custom error pages. In some cases, an object that is seldom requested is evicted and is no longer available in the edge cache. CloudFront can't serve an object that has been evicted. Redirects If you change the location of an object on the origin server, you can configure your web server to redirect requests to the new location. After you configure the redirect, the first time a viewer submits a request for |
AmazonCloudFront_DevGuide-122 | AmazonCloudFront_DevGuide.pdf | 122 | object or serves a custom error page. For more information about CloudFront behavior when you've configured custom error pages, see How CloudFront processes errors when you have configured custom error pages. In some cases, an object that is seldom requested is evicted and is no longer available in the edge cache. CloudFront can't serve an object that has been evicted. Redirects If you change the location of an object on the origin server, you can configure your web server to redirect requests to the new location. After you configure the redirect, the first time a viewer submits a request for the object, CloudFront sends the request to the origin, and the origin How CloudFront processes responses from your custom origin 314 Amazon CloudFront Developer Guide responds with a redirect (for example, 302 Moved Temporarily). CloudFront caches the redirect and returns it to the viewer. CloudFront does not follow the redirect. You can configure your web server to redirect requests to one of the following locations: • The new URL of the object on the origin server. When the viewer follows the redirect to the new URL, the viewer bypasses CloudFront and goes straight to the origin. As a result, we recommend that you don't redirect requests to the new URL of the object on the origin. • The new CloudFront URL for the object. When the viewer submits the request that contains the new CloudFront URL, CloudFront gets the object from the new location on your origin, caches it at the edge location, and returns the object to the viewer. Subsequent requests for the object will be served by the edge location. This avoids the latency and load associated with viewers requesting the object from the origin. However, every new request for the object will incur charges for two requests to CloudFront. Transfer-Encoding header CloudFront supports only the chunked value of the Transfer-Encoding header. If your origin returns Transfer-Encoding: chunked, CloudFront returns the object to the client as the object is received at the edge location, and caches the object in chunked format for subsequent requests. If the viewer makes a Range GET request and the origin returns Transfer-Encoding: chunked, CloudFront returns the entire object to the viewer instead of the requested range. We recommend that you use chunked encoding if the content length of your response cannot be predetermined. For more information, see Dropped TCP connections. Request and response behavior for origin groups Requests to an origin group work the same as requests to an origin that is not set up as an origin group, except when there is an origin failover. As with any other origin, when CloudFront receives a request and the content is already cached in an edge location, the content is served to viewers from the cache. When there’s a cache miss and the origin is an origin group, viewer requests are forwarded to the primary origin in the origin group. The request and response behavior for the primary origin is the same as it is for an origin that isn’t in an origin group. For more information, see Request and response behavior for Amazon S3 origins and Request and response behavior for custom origins. Request and response behavior for origin groups 315 Amazon CloudFront Developer Guide The following describes the behavior for origin failover when the primary origin returns specific HTTP status codes: • HTTP 2xx status code (success): CloudFront caches the file and returns it to the viewer. • HTTP 3xx status code (redirection): CloudFront returns the status code to the viewer. • HTTP 4xx or 5xx status code (client/server error): If the returned status code has been configured for failover, CloudFront sends the same request to the secondary origin in the origin group. • HTTP 4xx or 5xx status code (client/server error): If the returned status code has not been configured for failover, CloudFront returns the error to the viewer. CloudFront fails over to the secondary origin only when the HTTP method of the viewer request is GET, HEAD, or OPTIONS. CloudFront does not fail over when the viewer sends a different HTTP method (for example POST, PUT, and so on). When CloudFront sends a request to a secondary origin, the response behavior is the same as for a CloudFront origin that’s not in an origin group. For more information about origin groups, see Optimize high availability with CloudFront origin failover. Add custom headers to origin requests You can configure CloudFront to add custom headers to the requests that it sends to your origin. You can use custom headers to send and gather information from your origin that you don’t get with typical viewer requests. You can even customize the headers for each origin. CloudFront supports custom headers for custom origins and Amazon S3 origins. Contents • Use cases • Configure CloudFront |
AmazonCloudFront_DevGuide-123 | AmazonCloudFront_DevGuide.pdf | 123 | behavior is the same as for a CloudFront origin that’s not in an origin group. For more information about origin groups, see Optimize high availability with CloudFront origin failover. Add custom headers to origin requests You can configure CloudFront to add custom headers to the requests that it sends to your origin. You can use custom headers to send and gather information from your origin that you don’t get with typical viewer requests. You can even customize the headers for each origin. CloudFront supports custom headers for custom origins and Amazon S3 origins. Contents • Use cases • Configure CloudFront to add custom headers to origin requests • Custom headers that CloudFront can’t add to origin requests • Configure CloudFront to forward the Authorization header Use cases You can use custom headers, such as the following examples: Add custom headers to origin requests 316 Amazon CloudFront Developer Guide Identifying requests from CloudFront You can identify the requests that your origin receives from CloudFront. This can be useful if you want to know if users are bypassing CloudFront, or if you’re using more than one CDN and you want information about which requests are coming from each CDN. Note If you’re using an Amazon S3 origin and you enable Amazon S3 server access logging, the logs don’t include header information. Determining which requests come from a particular distribution If you configure more than one CloudFront distribution to use the same origin, you can add different custom headers in each distribution. You can then use the logs from your origin to determine which requests came from which CloudFront distribution. Enabling cross-origin resource sharing (CORS) If some of your viewers don’t support cross-origin resource sharing (CORS), you can configure CloudFront to always add the Origin header to requests that it sends to your origin. Then you can configure your origin to return the Access-Control-Allow-Origin header for every request. You must also configure CloudFront to respect CORS settings. Controlling access to content You can use custom headers to control access to content. By configuring your origin to respond to requests only when they include a custom header that gets added by CloudFront, you prevent users from bypassing CloudFront and accessing your content directly on the origin. For more information, see Restrict access to files on custom origins. Configure CloudFront to add custom headers to origin requests To configure a distribution to add custom headers to requests that it sends to your origin, update the origin configuration using one of the following methods: • CloudFront console – When you create or update a distribution, specify header names and values in the Add custom headers settings. For more information, see Add custom header. Configure CloudFront to add custom headers to origin requests 317 Amazon CloudFront Developer Guide • CloudFront API – For each origin that you want to add custom headers to, specify the header names and values in the CustomHeaders field inside Origin. For more information, see CreateDistribution or UpdateDistribution in the Amazon CloudFront API Reference. If the header names and values that you specify are not already present in the viewer request, CloudFront adds them to the origin request. If a header is present, CloudFront overwrites the header value before forwarding the request to the origin. For the quotas that apply to origin custom headers, see Quotas on headers. Custom headers that CloudFront can’t add to origin requests You can’t configure CloudFront to add any of the following headers to requests that it sends to your origin: • Cache-Control • Connection • Content-Length • Cookie • Host • If-Match • If-Modified-Since • If-None-Match • If-Range • If-Unmodified-Since • Max-Forwards • Pragma • Proxy-Authenticate • Proxy-Authorization • Proxy-Connection • Range • Request-Range • TE Custom headers that CloudFront can’t add to origin requests 318 Developer Guide Amazon CloudFront • Trailer • Transfer-Encoding • Upgrade • Via • Headers that begin with X-Amz- • Headers that begin with X-Edge- • X-Real-Ip Configure CloudFront to forward the Authorization header When CloudFront forwards a viewer request to your origin, CloudFront removes some viewer headers by default, including the Authorization header. To make sure that your origin always receives the Authorization header in origin requests, you have the following options: • Add the Authorization header to the cache key using a cache policy. All headers in the cache key are automatically included in origin requests. For more information, see Control the cache key with a policy. • Use an origin request policy that forwards all viewer headers to the origin. You cannot forward the Authorization header individually in an origin request policy, but when you forward all viewer headers CloudFront includes the Authorization header in viewer requests. CloudFront provides a managed origin request policy for this use case, called Managed-AllViewer. For more information, see Use managed origin request policies. |
AmazonCloudFront_DevGuide-124 | AmazonCloudFront_DevGuide.pdf | 124 | options: • Add the Authorization header to the cache key using a cache policy. All headers in the cache key are automatically included in origin requests. For more information, see Control the cache key with a policy. • Use an origin request policy that forwards all viewer headers to the origin. You cannot forward the Authorization header individually in an origin request policy, but when you forward all viewer headers CloudFront includes the Authorization header in viewer requests. CloudFront provides a managed origin request policy for this use case, called Managed-AllViewer. For more information, see Use managed origin request policies. How CloudFront processes partial requests for an object (range GETs) For a large object, the viewer (web browser or other client) can make multiple GET requests and use the Range request header to download the object in smaller parts. These requests for ranges of bytes, sometimes known as Range GET requests, improve the efficiency of partial downloads and the recovery from partially failed transfers. When CloudFront receives a Range GET request, it checks the cache in the edge location that received the request. If the cache in that edge location already contains the entire object or the requested part of the object, CloudFront immediately serves the requested range from the cache. Configure CloudFront to forward the Authorization header 319 Amazon CloudFront Developer Guide If the cache doesn’t contain the requested range, CloudFront forwards the request to the origin. (To optimize performance, CloudFront may request a larger range than the client requested in the Range GET.) What happens next depends on whether the origin supports Range GET requests: • If the origin supports Range GET requests – It returns the requested range. CloudFront serves the requested range and also caches it for future requests. (Amazon S3 supports Range GET requests, as do many HTTP servers.) • If the origin doesn’t support Range GET requests – It returns the entire object. CloudFront serves the current request by sending the entire object while also caching it for future requests. After CloudFront caches the entire object in an edge cache, it responds to new Range GET requests by serving the requested range. In either case, CloudFront begins to serve the requested range or object to the end user as soon as the first byte arrives from the origin. Note If the viewer makes a Range GET request and the origin returns Transfer-Encoding: chunked, CloudFront returns the entire object to the viewer instead of the requested range. CloudFront generally follows the RFC specification for the Range header. However, if your Range headers don’t adhere to the following requirements, CloudFront returns HTTP status code 200 with the full object instead of status code 206 with the specified ranges: • The ranges must be listed in ascending order. For example, 100-200,300-400 is valid, 300-400,100-200 is not valid. • The ranges must not overlap. For example, 100-200,150-250 is not valid. • All of the ranges specifications must be valid. For example, you can’t specify a negative value as part of a range. For more information about the Range request header, see Range Requests in RFC 7233, or Range in the MDN Web Docs. How CloudFront processes range GETs 320 Amazon CloudFront Developer Guide Use range requests to cache large objects When caching is enabled, CloudFront doesn’t retrieve or cache an object that is larger than 50 GB. When an origin indicates that the object is larger than this size (in the Content-Length response header), CloudFront closes the connection to the origin and returns an error to the viewer. (With caching disabled, CloudFront can retrieve an object that is larger than this size from the origin and pass it along to the viewer. However, CloudFront doesn’t cache the object.) However, with range requests, you can use CloudFront to cache an object that is larger than the maximum cacheable file size. Example Example 1. Consider an origin with a 100 GB object. With caching enabled, CloudFront doesn’t retrieve or cache an object this large. However, the viewer can send multiple range requests to retrieve this object in parts, with each part smaller than 50 GB. 2. The viewer can request the object in 20 GB parts by sending a request with the header Range: bytes=0-21474836480 to retrieve the first part, another request with the header Range: bytes=21474836481-42949672960 to retrieve the next part, and so on. 3. When the viewer has received all of the parts, it can combine them to construct the original 100 GB object. 4. In this case, CloudFront caches each of the 20 GB parts of the object and can respond to subsequent requests for the same part from the cache. For a range request for a compressed object, the byte range request is based on the compressed size, and not the original size of the object. |
AmazonCloudFront_DevGuide-125 | AmazonCloudFront_DevGuide.pdf | 125 | with the header Range: bytes=0-21474836480 to retrieve the first part, another request with the header Range: bytes=21474836481-42949672960 to retrieve the next part, and so on. 3. When the viewer has received all of the parts, it can combine them to construct the original 100 GB object. 4. In this case, CloudFront caches each of the 20 GB parts of the object and can respond to subsequent requests for the same part from the cache. For a range request for a compressed object, the byte range request is based on the compressed size, and not the original size of the object. For more information about compressing files, see Serve compressed files. How CloudFront processes HTTP 3xx status codes from your origin When CloudFront requests an object from your Amazon S3 bucket or custom origin server, your origin sometimes returns an HTTP 3xx status code. This typically indicates one of the following: • The object’s URL has changed (for example, status codes 301, 302, 307, or 308) • The object hasn’t changed since the last time CloudFront requested it (status code 304) Use range requests to cache large objects 321 Amazon CloudFront Developer Guide CloudFront caches 3xx responses according to the settings in your CloudFront distribution and the headers in the response. CloudFront caches 307 and 308 responses only when you include the Cache-Control header in responses from the origin. For more information, see Manage how long content stays in the cache (expiration). If your origin returns a redirect status code (for example, 301 or 307), CloudFront doesn’t follow the redirect. CloudFront passes along the 301 or 307 response to the viewer, who can follow the redirect by sending a new request. How CloudFront processes HTTP 4xx and 5xx status codes from your origin When CloudFront requests an object from your Amazon S3 bucket or custom origin server, your origin sometimes returns an HTTP 4xx or 5xx status code, which indicates that an error has occurred. CloudFront behavior depends on: • Whether you have configured custom error pages • Whether you have configured how long you want CloudFront to cache error responses from your origin (error caching minimum TTL) • The status code • For 5xx status codes, whether the requested object is currently in the CloudFront edge cache • For some 4xx status codes, whether the origin returns a Cache-Control max-age or Cache- Control s-maxage header CloudFront always caches responses to GET and HEAD requests. You can also configure CloudFront to cache responses to OPTIONS requests. CloudFront does not cache responses to requests that use the other methods. If the origin doesn't respond, the CloudFront request to the origin times out which is considered an HTTP 5xx error from the origin, even though the origin didn't respond with that error. In that scenario, CloudFront continues to serve cached content. For more information, see Origin unavailable. If you have enabled logging, CloudFront writes the results to the logs regardless of the HTTP status code. How CloudFront processes HTTP 4xx and 5xx status codes from your origin 322 Amazon CloudFront Developer Guide For more information about features and options that relate to the error message returned from CloudFront, see the following: • For information about settings for custom error pages in the CloudFront console, see Custom error pages and error caching. • For information about the error caching minimum TTL in the CloudFront console, see Error caching minimum TTL (seconds). • For a list of the HTTP status codes that CloudFront caches, see HTTP 4xx and 5xx status codes that CloudFront caches. Topics • How CloudFront processes errors when you have configured custom error pages • How CloudFront processes errors if you haven't configured custom error pages • HTTP 4xx and 5xx status codes that CloudFront caches How CloudFront processes errors when you have configured custom error pages If you have configured custom error pages, CloudFront behavior depends on whether the requested object is in the edge cache. The requested object is not in the edge cache CloudFront continues to try to get the requested object from your origin when all of the following are true: • A viewer requests an object. • The object isn't in the edge cache. • Your origin returns an HTTP 4xx or 5xx status code and one of the following is true: • Your origin returns an HTTP 5xx status code instead of returning a 304 status code (Not Modified) or an updated version of the object. • Your origin returns an HTTP 4xx status code that is not restricted by a cache control header and is included in the following list of status codes: HTTP 4xx and 5xx status codes that CloudFront caches. How CloudFront processes errors when you have configured custom error pages 323 Amazon CloudFront Developer Guide • Your origin returns an HTTP 4xx |
AmazonCloudFront_DevGuide-126 | AmazonCloudFront_DevGuide.pdf | 126 | returns an HTTP 4xx or 5xx status code and one of the following is true: • Your origin returns an HTTP 5xx status code instead of returning a 304 status code (Not Modified) or an updated version of the object. • Your origin returns an HTTP 4xx status code that is not restricted by a cache control header and is included in the following list of status codes: HTTP 4xx and 5xx status codes that CloudFront caches. How CloudFront processes errors when you have configured custom error pages 323 Amazon CloudFront Developer Guide • Your origin returns an HTTP 4xx status code without a Cache-Control max-age header or a Cache-Control s-maxage header, and the status code is included in the following list of status codes: Control HTTP 4xx status codes that CloudFront caches based on Cache- Control headers. CloudFront does the following: 1. In the CloudFront edge cache that received the viewer request, CloudFront checks your distribution configuration and gets the path of the custom error page that corresponds with the status code that your origin returned. 2. CloudFront finds the first cache behavior in your distribution that has a path pattern that matches the path of the custom error page. 3. The CloudFront edge location sends a request for the custom error page to the origin that is specified in the cache behavior. 4. The origin returns the custom error page to the edge location. 5. CloudFront returns the custom error page to the viewer that made the request, and also caches the custom error page for the maximum of the following: • The amount of time specified by the error caching minimum TTL (10 seconds by default) • The amount of time specified by a Cache-Control max-age header or a Cache-Control s-maxage header that is returned by the origin when the first request generated the error 6. After the caching time (determined in Step 5) has elapsed, CloudFront tries again to get the requested object by forwarding another request to your origin. CloudFront continues to retry at intervals specified by the error caching minimum TTL. The requested object is in the edge cache CloudFront continues to serve the object that is currently in the edge cache when all of the following are true: • A viewer requests an object. • The object is in the edge cache but it has expired. • Your origin returns an HTTP 5xx status code instead of returning a 304 status code (Not Modified) or an updated version of the object. How CloudFront processes errors when you have configured custom error pages 324 Amazon CloudFront CloudFront does the following: Developer Guide 1. If your origin returns a 5xx status code, CloudFront serves the object even though it has expired. For the duration of the error caching minimum TTL, CloudFront continues to respond to viewer requests by serving the object from the edge cache. If your origin returns a 4xx status code, CloudFront returns the status code, not the requested object, to the viewer. 2. After the error caching minimum TTL has elapsed, CloudFront tries again to get the requested object by forwarding another request to your origin. Note that if the object is not requested frequently, CloudFront might evict it from the edge cache while your origin server is still returning 5xx responses. For information about how long objects stay in CloudFront edge caches, see Manage how long content stays in the cache (expiration). How CloudFront processes errors if you haven't configured custom error pages If you haven't configured custom error pages, CloudFront behavior depends on whether the requested object is in the edge cache. Topics • The requested object is not in the edge cache • The requested object is in the edge cache The requested object is not in the edge cache CloudFront continues to try to get the requested object from your origin when all of the following are true: • A viewer requests an object. • The object isn't in the edge cache. • Your origin returns an HTTP 4xx or 5xx status code and one of the following is true: • Your origin returns an HTTP 5xx status code instead of returning a 304 status code (Not Modified) or an updated version of the object. How CloudFront processes errors if you haven't configured custom error pages 325 Amazon CloudFront Developer Guide • Your origin returns an HTTP 4xx status code that is not restricted by a cache control header and is included in the following list of status codes: HTTP 4xx and 5xx status codes that CloudFront caches • Your origin returns an HTTP 4xx status code without a Cache-Control max-age header or a Cache-Control s-maxage header and the status code is included in the following list of status codes: Control HTTP 4xx status codes that CloudFront caches |
AmazonCloudFront_DevGuide-127 | AmazonCloudFront_DevGuide.pdf | 127 | or an updated version of the object. How CloudFront processes errors if you haven't configured custom error pages 325 Amazon CloudFront Developer Guide • Your origin returns an HTTP 4xx status code that is not restricted by a cache control header and is included in the following list of status codes: HTTP 4xx and 5xx status codes that CloudFront caches • Your origin returns an HTTP 4xx status code without a Cache-Control max-age header or a Cache-Control s-maxage header and the status code is included in the following list of status codes: Control HTTP 4xx status codes that CloudFront caches based on Cache- Control headers. CloudFront does the following: 1. CloudFront returns the 4xx or 5xx status code to the viewer, and also caches status code in the edge cache that received the request for the maximum of the following: • The amount of time specified by the error caching minimum TTL (10 seconds by default) • The amount of time specified by a Cache-Control max-age header or a Cache-Control s-maxage header that is returned by the origin when the first request generated the error 2. For the duration of the caching time (determined in Step 1), CloudFront responds to subsequent viewer requests for the same object with the cached 4xx or 5xx status code. 3. After the caching time (determined in Step 1) has elapsed, CloudFront tries again to get the requested object by forwarding another request to your origin. CloudFront continues to retry at intervals specified by the error caching minimum TTL. The requested object is in the edge cache CloudFront continues to serve the object that is currently in the edge cache when all of the following are true: • A viewer requests an object. • The object is in the edge cache but it has expired. This means the object is stale. • Your origin returns an HTTP 5xx status code instead of returning a 304 status code (Not Modified) or an updated version of the object. CloudFront does the following: How CloudFront processes errors if you haven't configured custom error pages 326 Amazon CloudFront Developer Guide 1. If your origin returns a 5xx error code, CloudFront serves the object even though it has expired. For the duration of the error caching minimum TTL (10 seconds by default), CloudFront continues to respond to viewer requests by serving the object from the edge cache. If your origin returns a 4xx status code, CloudFront returns the status code, not the requested object, to the viewer. 2. After the error caching minimum TTL has elapsed, CloudFront tries again to get the requested object by forwarding another request to your origin. If the object isn't requested frequently, CloudFront might evict it from the edge cache while your origin server is still returning 5xx responses. For more information, see Manage how long content stays in the cache (expiration). Tip • If you configure the stale-if-error or Stale-While-Revalidate directive, you can specify how long the stale objects are available in the edge cache. This allows you to continue serving content for your viewers even when your origin is unavailable. For information, see Serve stale (expired) content. • CloudFront will only serve an object that is stale up to the specified maximum TTL value. After this duration, the object won't be available from the edge cache. HTTP 4xx and 5xx status codes that CloudFront caches CloudFront caches HTTP 4xx and 5xx status codes returned by your origin, depending on the specific status code that is returned and whether your origin returns specific headers in the response. CloudFront caches the following HTTP 4xx and 5xx status codes returned by your origin. If you configured a custom error page for an HTTP status code, CloudFront caches the custom error page. Note If you're using the CachingDisabled managed cache policy, CloudFront won't cache these status codes or custom error pages. HTTP 4xx and 5xx status codes that CloudFront caches 327 Amazon CloudFront Developer Guide 404 414 500 501 502 503 504 Not Found Request-URI Too Large Internal Server Error Not Implemented Bad Gateway Service Unavailable Gateway Time-out HTTP 4xx status codes that CloudFront caches based on Cache-Control headers CloudFront only caches the following HTTP 4xx status codes returned by your origin if your origin returns a Cache-Control max-age or Cache-Control s-maxage header. If you have configured a custom error page for one of these HTTP status codes – and your origin returns one of the cache control headers – CloudFront caches the custom error page. 400 403 405 412¹ 415¹ Bad Request Forbidden Method Not Allowed Precondition Failed Unsupported Media Type HTTP 4xx and 5xx status codes that CloudFront caches 328 Amazon CloudFront Developer Guide ¹CloudFront doesn't support creating custom error pages for these HTTP status codes. Generate custom error responses If an object that you’re |
AmazonCloudFront_DevGuide-128 | AmazonCloudFront_DevGuide.pdf | 128 | codes returned by your origin if your origin returns a Cache-Control max-age or Cache-Control s-maxage header. If you have configured a custom error page for one of these HTTP status codes – and your origin returns one of the cache control headers – CloudFront caches the custom error page. 400 403 405 412¹ 415¹ Bad Request Forbidden Method Not Allowed Precondition Failed Unsupported Media Type HTTP 4xx and 5xx status codes that CloudFront caches 328 Amazon CloudFront Developer Guide ¹CloudFront doesn't support creating custom error pages for these HTTP status codes. Generate custom error responses If an object that you’re serving through CloudFront is unavailable for some reason, your web server typically returns a relevant HTTP status code to CloudFront to indicate this. For example, if a viewer requests an invalid URL, your web server returns an HTTP 404 (Not Found) status code to CloudFront, and then CloudFront returns that status code to the viewer. Instead of using this default error response, you can create a custom one that CloudFront returns to the viewer. If you configure CloudFront to return a custom error page for an HTTP status code but the custom error page isn’t available, CloudFront returns to the viewer the status code that CloudFront received from the origin that contains the custom error pages. For example, suppose your custom origin returns a 500 status code and you have configured CloudFront to get a custom error page for a 500 status code from an Amazon S3 bucket. However, someone accidentally deleted the custom error page from your Amazon S3 bucket. CloudFront returns an HTTP 404 status code (Not Found) to the viewer that requested the object. When CloudFront returns a custom error page to a viewer, you pay the standard CloudFront charges for the custom error page, not the charges for the requested object. For more information about CloudFront charges, see Amazon CloudFront Pricing. Topics • Configure error response behavior • Create a custom error page for specific HTTP status codes • Store objects and custom error pages in different locations • Change response codes returned by CloudFront • Control how long CloudFront caches errors Configure error response behavior You have several options to manage how CloudFront responds when there’s an error. To configure custom error responses, you can use the CloudFront console, the CloudFront API, or AWS CloudFormation. Regardless of how you choose to update the configuration, consider the following tips and recommendations: Generate custom error responses 329 Amazon CloudFront Developer Guide • Save your custom error pages in a location that is accessible to CloudFront. We recommend that you store them in an Amazon S3 bucket, and that you don’t store them in the same place as the rest of your website or application’s content. If you store the custom error pages on the same origin as your website or application, and the origin starts to return 5xx errors, CloudFront can’t get the custom error pages because the origin server is unavailable. For more information, see Store objects and custom error pages in different locations. • Make sure that CloudFront has permission to get your custom error pages. If the custom error pages are stored in Amazon S3, the pages must be publicly accessible or you must configure a CloudFront origin access control (OAC). If the custom error pages are stored in a custom origin, the pages must be publicly accessible. • (Optional) Configure your origin to add a Cache-Control or Expires header along with the custom error pages, if you want. You can also use the Error Caching Minimum TTL setting to control how long CloudFront caches the custom error pages. For more information, see Control how long CloudFront caches errors. Configure custom error responses To configure custom error responses in the CloudFront console, you must have a CloudFront distribution. In the console, the configuration settings for custom error responses are only available for existing distributions. To learn how to create a distribution, see Get started with a basic CloudFront distribution. Console To configure custom error responses (console) 1. Sign in to the AWS Management Console and open the Distributions page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/ home#distributions. 2. In the list of distributions, choose the distribution to update. 3. Choose the Error Pages tab, then choose Create Custom Error Response. 4. Enter the applicable values. For more information, see Custom error pages and error caching. 5. After entering the desired values, choose Create. Configure error response behavior 330 Amazon CloudFront Developer Guide CloudFront API or AWS CloudFormation To configure custom error responses with the CloudFront API or AWS CloudFormation, use the CustomErrorResponse type in a distribution. For more information, see the following: • AWS::CloudFront::Distribution CustomErrorResponse in the AWS CloudFormation User Guide • CustomErrorResponse in the Amazon CloudFront API Reference Create a custom error page for |
AmazonCloudFront_DevGuide-129 | AmazonCloudFront_DevGuide.pdf | 129 | distribution to update. 3. Choose the Error Pages tab, then choose Create Custom Error Response. 4. Enter the applicable values. For more information, see Custom error pages and error caching. 5. After entering the desired values, choose Create. Configure error response behavior 330 Amazon CloudFront Developer Guide CloudFront API or AWS CloudFormation To configure custom error responses with the CloudFront API or AWS CloudFormation, use the CustomErrorResponse type in a distribution. For more information, see the following: • AWS::CloudFront::Distribution CustomErrorResponse in the AWS CloudFormation User Guide • CustomErrorResponse in the Amazon CloudFront API Reference Create a custom error page for specific HTTP status codes If you’d rather display a custom error message instead of the default message—for example, a page that uses the same formatting as the rest of your website—you can have CloudFront return to the viewer an object (such as an HTML file) that contains your custom error message. To specify the file that you want to return and the errors for which the file should be returned, you update your CloudFront distribution to specify those values. For more information, see Configure error response behavior. For example, the following is a custom error page: Create a custom error page for specific HTTP status codes 331 Amazon CloudFront Developer Guide You can specify a different object for each supported HTTP status code, or you can use the same object for all of the supported status codes. You can choose to specify custom error pages for some status codes and not for others. The objects that you’re serving through CloudFront can be unavailable for a variety of reasons. These fall into two broad categories: • Client errors indicate a problem with the request. For example, an object with the specified name isn’t available, or the user doesn’t have the permissions required to get an object in your Amazon S3 bucket. When a client error occurs, the origin returns an HTTP status code in the 4xx range to CloudFront. • Server errors indicate a problem with the origin server. For example, the HTTP server is busy or unavailable. When a server error occurs, either your origin server returns an HTTP status code in the 5xx range to CloudFront, or CloudFront doesn’t get a response from your origin server for a certain period of time and assumes a 504 status code (Gateway Timeout). The HTTP status codes for which CloudFront can return a custom error page include the following: • 400, 403, 404, 405, 414, 416 • 500, 501, 502, 503, 504 Notes • If CloudFront detects that the request might be unsafe, CloudFront returns a 400 (Bad Request) error instead of a custom error page. • You can create a custom error page for HTTP status code 416 (Requested Range Not Satisfiable), and you can change the HTTP status code that CloudFront returns to viewers when your origin returns a status code 416 to CloudFront. For more information, see Change response codes returned by CloudFront. However, CloudFront doesn't cache status code 416 responses, so even if you specify a value for Error Caching Minimum TTL for status code 416, CloudFront doesn't use it. • In some cases, CloudFront doesn’t return a custom error page for the HTTP 503 status code even if you configure CloudFront to do so. If the CloudFront error code is Capacity Exceeded or Limit Exceeded, CloudFront returns a 503 status code to the viewer without using your custom error page. • If you created a custom error page, CloudFront will return Connection: close or Connection: keep-alive for the following response codes: Create a custom error page for specific HTTP status codes 332 Amazon CloudFront Developer Guide • CloudFront returns Connection: close for status codes: 400, 405, 414, 416, 500, 501 • CloudFront returns Connection: keep-alive for status codes: 403, 404, 502, 503, 504 For a detailed explanation of how CloudFront handles error responses from your origin, see How CloudFront processes HTTP 4xx and 5xx status codes from your origin. Store objects and custom error pages in different locations If you want to store your objects and your custom error pages in different locations, your distribution must include a cache behavior for which the following is true: • The value of Path Pattern matches the path to your custom error messages. For example, suppose you saved custom error pages for 4xx errors in an Amazon S3 bucket in a directory named /4xx-errors. Your distribution must include a cache behavior for which the path pattern routes requests for your custom error pages to that location, for example, /4xx- errors/*. • The value of Origin specifies the value of Origin ID for the origin that contains your custom error pages. For more information, see Cache behavior settings. Change response codes returned by CloudFront You can configure CloudFront to return a |
AmazonCloudFront_DevGuide-130 | AmazonCloudFront_DevGuide.pdf | 130 | The value of Path Pattern matches the path to your custom error messages. For example, suppose you saved custom error pages for 4xx errors in an Amazon S3 bucket in a directory named /4xx-errors. Your distribution must include a cache behavior for which the path pattern routes requests for your custom error pages to that location, for example, /4xx- errors/*. • The value of Origin specifies the value of Origin ID for the origin that contains your custom error pages. For more information, see Cache behavior settings. Change response codes returned by CloudFront You can configure CloudFront to return a different HTTP status code to the viewer than what CloudFront received from the origin. For example, if your origin returns a 500 status code to CloudFront, you might want CloudFront to return a custom error page and a 200 status code (OK) to the viewer. There are a variety of reasons that you might want CloudFront to return a status code to the viewer that is different from the one that your origin returned to CloudFront: • Some internet devices (some firewalls and corporate proxies, for example) intercept HTTP 4xx and 5xx status codes and prevent the response from being returned to the viewer. In this scenario, if you substitute 200, the response is not intercepted. • If you don’t care about distinguishing among different client errors or server errors, you can specify 400 or 500 as the value that CloudFront returns for all 4xx or 5xx status codes. Store objects and custom error pages in different locations 333 Amazon CloudFront Developer Guide • You might want to return a 200 status code (OK) and a static website so your customers don’t know that your website is down. If you enable CloudFront standard logs and you configure CloudFront to change the HTTP status code in the response, the value of the sc-status column in the logs contains the status code that you specify. However, the value of the x-edge-result-type column is not affected. It contains the result type of the response from the origin. For example, suppose you configure CloudFront to return a status code of 200 to the viewer when the origin returns 404 (Not Found) to CloudFront. When the origin responds to a request with a 404 status code, the value in the sc-status column in the log will be 200, but the value in the x-edge-result-type column will be Error. You can configure CloudFront to return any of the following HTTP status codes along with a custom error page: • 200 • 400, 403, 404, 405, 414, 416 • 500, 501, 502, 503, 504 Control how long CloudFront caches errors CloudFront caches error responses for a default duration of 10 seconds. CloudFront then submits the next request for the object to your origin to see if the problem that caused the error has been resolved and the requested object is available. You can specify the error-caching duration—the Error Caching Minimum TTL—for each 4xx and 5xx status code that CloudFront caches. (For more information, see HTTP 4xx and 5xx status codes that CloudFront caches.) When you specify a duration, note the following: • If you specify a short error-caching duration, CloudFront forwards more requests to your origin than if you specify a longer duration. For 5xx errors, this might aggravate the problem that originally caused your origin to return an error. • When your origin returns an error for an object, CloudFront responds to requests for the object either with the error response or with your custom error page until the error-caching duration elapses. If you specify a long error-caching duration, CloudFront might continue to respond to requests with an error response or your custom error page for a long time after the object becomes available again. Control how long CloudFront caches errors 334 Amazon CloudFront Note Developer Guide You can create a custom error page for HTTP status code 416 (Requested Range Not Satisfiable), and you can change the HTTP status code that CloudFront returns to viewers when your origin returns a status code 416 to CloudFront. (For more information, see Change response codes returned by CloudFront.) However, CloudFront doesn't cache status code 416 responses, so even if you specify a value for Error Caching Minimum TTL for status code 416, CloudFront doesn't use it. If you want to control how long CloudFront caches errors for individual objects, you can configure your origin server to add the applicable header to the error response for that object. If the origin adds a Cache-Control: max-age or Cache-Control: s-maxage directive, or an Expires header, CloudFront caches error responses for the greater of the value in the header or the Error Caching Minimum TTL. Note The Cache-Control: max-age and Cache-Control: s-maxage values cannot be greater than the Maximum TTL value set |
AmazonCloudFront_DevGuide-131 | AmazonCloudFront_DevGuide.pdf | 131 | if you specify a value for Error Caching Minimum TTL for status code 416, CloudFront doesn't use it. If you want to control how long CloudFront caches errors for individual objects, you can configure your origin server to add the applicable header to the error response for that object. If the origin adds a Cache-Control: max-age or Cache-Control: s-maxage directive, or an Expires header, CloudFront caches error responses for the greater of the value in the header or the Error Caching Minimum TTL. Note The Cache-Control: max-age and Cache-Control: s-maxage values cannot be greater than the Maximum TTL value set for the cache behavior for which the error page is being fetched. If the origin adds other Cache-Control directives or adds no headers, CloudFront caches error responses for the value of Error Caching Minimum TTL. If the expiration time for a 4xx or 5xx status code for an object is longer than you want, and the object is available again, you can invalidate cached error code by using the URL of the requested object. If your origin is returning an error response for multiple objects, you need to invalidate each object separately. For more information about invalidating objects, see Invalidate files to remove content. If you have caching enabled for an S3 bucket origin, and you configure an error caching minimum TTL of 0 seconds in your CloudFront distribution, you will still see an error caching minimum TTL of 1 second for S3 origin errors. CloudFront does this to protect your origin from DDoS attacks. This doesn't apply to other types of origins. Control how long CloudFront caches errors 335 Amazon CloudFront Developer Guide Add, remove, or replace content that CloudFront distributes This section explains how to make sure CloudFront can access the content that you want to be served to your viewers, how to specify the objects in your website or in your application, and how to remove or replace content. Topics • Add and access content that CloudFront distributes • Use file versioning to update or remove content with a CloudFront distribution • Customize the URL format for files in CloudFront • Specify a default root object • Invalidate files to remove content • Serve compressed files Add and access content that CloudFront distributes When you want CloudFront to distribute content (objects), you add files to one of the origins that you specified for the distribution, and you expose a CloudFront link to the files. A CloudFront edge location doesn't fetch the new files from an origin until the edge location receives viewer requests for them. For more information, see How CloudFront delivers content. When you add a file that you want CloudFront to distribute, make sure that you add it to one of the Amazon S3 buckets specified in your distribution or, for a custom origin, to a directory in the specified domain. In addition, confirm that the path pattern in the applicable cache behavior sends requests to the correct origin. For example, suppose the path pattern for a cache behavior is *.html. If you don't have any other cache behaviors configured to forward requests to that origin, CloudFront will only forward *.html files. In this scenario, for example, CloudFront will never distribute .jpg files that you upload to the origin, because you haven't created a cache behavior that includes .jpg files. CloudFront servers don't determine the MIME type for the objects that they serve. When you upload a file to your origin, we recommend that you set the Content-Type header field for it. Add and access content 336 Amazon CloudFront Developer Guide Use file versioning to update or remove content with a CloudFront distribution To update existing content that CloudFront is set up to distribute for you, we recommend that you use a version identifier in file names or in folder names. This helps give you control over managing the content that CloudFront serves. Update existing files using versioned file names When you update existing files in a CloudFront distribution, we recommend that you include some sort of version identifier either in your file names or in your directory names to give yourself better control over your content. This identifier might be a date-time stamp, a sequential number, or some other method of distinguishing two versions of the same object. 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. Alternatively, you might put all graphics in an images_v1 directory and, when you want to start serving new versions of one or more graphics, you'd create a new images_v2 directory, and you'd update your links to point to that |
AmazonCloudFront_DevGuide-132 | AmazonCloudFront_DevGuide.pdf | 132 | sequential number, or some other method of distinguishing two versions of the same object. 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. Alternatively, you might put all graphics in an images_v1 directory and, when you want to start serving new versions of one or more graphics, you'd create a new images_v2 directory, and you'd update your links to point to that directory. With versioning, you don't have to wait for an object to expire before CloudFront begins to serve a new version of it, and you don't have to pay for object invalidation. Even if you version your files, we still recommend that you set an expiration date. For more information, see Manage how long content stays in the cache (expiration). Note Specifying versioned file names or directory names is not related to Amazon S3 object versioning. Remove content so CloudFront won’t distribute it You can remove files from your origin that you no longer want to be included in your CloudFront distribution. However, CloudFront will continue to show viewers content from the edge cache until the files expire. If you want to remove a file right away, you must do one of the following: Use file versioning to update or remove existing content 337 Amazon CloudFront Developer Guide • Use file versioning. When you use versioning, different versions of a file have different names that you can use in your CloudFront distribution, to change which file is returned to viewers. For more information, see Update existing files using versioned file names. • Invalidate the file. For more information, see Invalidate files to remove content. Customize the URL format for files in CloudFront After you set up your origin with the objects (content) that you want CloudFront to serve to your viewers, you must use the correct URLs to reference those objects in your website or application code so that CloudFront can serve it. The domain name that you use in the URLs for objects on your web pages or in your web application can be either of the following: • The domain name, such as d111111abcdef8.cloudfront.net, that CloudFront automatically assigns when you create a distribution • Your own domain name, such as example.com For example, you might use one of the following URLs to return the file image.jpg: https://d111111abcdef8.cloudfront.net/images/image.jpg https://example.com/images/image.jpg You use the same URL format whether you store the content in Amazon S3 buckets or at a custom origin, like one of your own web servers. Note The URL format depends in part on the value that you specify for Origin Path in your distribution. This value gives CloudFront a top directory path for your objects. For more information about setting the origin path when you create a distribution, see Origin path. For more information about URL formats, see the following sections. Customize file URLs 338 Amazon CloudFront Developer Guide Use your own domain name (example.com) Instead of using the default domain name that CloudFront assigns for you when you create a distribution, you can add an alternate domain name that's easier to work with, like example.com. By setting up your own domain name with CloudFront, you can use a URL like this for objects in your distribution: https://example.com/images/image.jpg If you plan to use HTTPS between viewers and CloudFront, see Use alternate domain names and HTTPS. Use a trailing slash (/) in URLs When you specify URLs for directories in your CloudFront distribution, choose either to always use a trailing slash or to never use a trailing slash. For example, choose only one of the following formats for all of your URLs: https://d111111abcdef8.cloudfront.net/images/ https://d111111abcdef8.cloudfront.net/images Why does it matter? Both formats work to link to CloudFront objects, but being consistent can help prevent issues when you want to invalidate a directory later. CloudFront stores URLs exactly as they are defined, including trailing slashes. So if your format is inconsistent, you'll need to invalidate directory URLs with and without the slash, to ensure that CloudFront removes the directory. It’s inconvenient to have to invalidate both URL formats, and it can lead to additional costs. That’s because if you must double up invalidations to cover both types of URLs, you might exceed the maximum number of free invalidations allowed for the month. And if that happens, you'll have to pay for all the invalidations, even if only one format for each directory URL exists in CloudFront. Create signed URLs for restricted content If you have content that you want to restrict access to, you can create signed URLs. For example, if you want to distribute your content only to users who have |
AmazonCloudFront_DevGuide-133 | AmazonCloudFront_DevGuide.pdf | 133 | have to invalidate both URL formats, and it can lead to additional costs. That’s because if you must double up invalidations to cover both types of URLs, you might exceed the maximum number of free invalidations allowed for the month. And if that happens, you'll have to pay for all the invalidations, even if only one format for each directory URL exists in CloudFront. Create signed URLs for restricted content If you have content that you want to restrict access to, you can create signed URLs. For example, if you want to distribute your content only to users who have authenticated, you can create URLs that are valid only for a specified time period or that are available only from a specified IP address. For more information, see Serve private content with signed URLs and signed cookies. Use your own domain name (example.com) 339 Amazon CloudFront Developer Guide Specify a default root object You can configure CloudFront to return a specific object (the default root object) when a user (viewer) requests the root URL for your distribution instead of requesting an object in your distribution. You can use a default root object to avoid exposing the contents of your distribution. Contents • How to specify a default root object • How default root object works • How CloudFront works if you don’t define a root object How to specify a default root object To avoid exposing the contents of your distribution or returning an error, specify a default root object for your distribution. You can specify the exact file name or the path to the file. For example, if your root object is an index.html file, you can specify that file name. If your index.html file is in another folder, specify the path instead such as exampleFolderName/index.html. If you set a path to the default root object, viewer requests to the root URL of the distribution will return the specified file from that path. You can use a file path to have more flexibility to organize your content at the origin, as your default root object can be in a folder instead of at the root level. To specify a default root object for your distribution 1. Upload the default root object to the origin that your distribution points to. The file can be any type supported by CloudFront. For a list of constraints on the file name, see the DefaultRootObject element in DistributionConfig of the Amazon CloudFront API Reference. Note If the file name of the default root object is too long or contains an invalid character, CloudFront returns the error HTTP 400 Bad Request - InvalidDefaultRootObject. In addition, CloudFront caches the code for 10 seconds (by default) and writes the results to the access logs. 2. Confirm that the permissions for the object grant CloudFront at least read access. Specify a default root object 340 Amazon CloudFront Developer Guide For more information about Amazon S3 permissions, see Identity and access management in Amazon S3 in the Amazon Simple Storage Service User Guide. 3. Update your distribution to refer to the default root object by using the CloudFront console or the CloudFront API. To specify a default root object by using the CloudFront console: a. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. b. c. d. In the list of distributions in the top pane, select the distribution to update. In the Settings pane, on the General tab, choose Edit. In the Edit settings dialog box, in the Default root object field, enter the file name or path to the default root object. Tip Your string can't begin with a forward slash (/). Only specify the object name or the path to the object. For example, use index.html or exampleFolderName/ index.html. Specifying a /exampleFolderName/index.html or /index.html can lead to a 403 Access Denied error. e. Choose Save changes. To update your configuration using the CloudFront API, specify a value for the DefaultRootObject element in your distribution. For information about using the CloudFront API to specify a default root object, see UpdateDistribution in the Amazon CloudFront API Reference. 4. Confirm that you have enabled the default root object by requesting your root URL. If your browser doesn't display the default root object, perform the following steps: a. Confirm that your distribution is fully deployed by viewing the status of your distribution in the CloudFront console. b. Repeat steps 2 and 3 to verify that you granted the correct permissions and that you correctly updated the configuration of your distribution to specify the default root object. How to specify a default root object 341 Amazon CloudFront Developer Guide How default root object works Suppose the following request points to the object image.jpg: https://d111111abcdef8.cloudfront.net/image.jpg In contrast, the following request points to the root URL of |
AmazonCloudFront_DevGuide-134 | AmazonCloudFront_DevGuide.pdf | 134 | If your browser doesn't display the default root object, perform the following steps: a. Confirm that your distribution is fully deployed by viewing the status of your distribution in the CloudFront console. b. Repeat steps 2 and 3 to verify that you granted the correct permissions and that you correctly updated the configuration of your distribution to specify the default root object. How to specify a default root object 341 Amazon CloudFront Developer Guide How default root object works Suppose the following request points to the object image.jpg: https://d111111abcdef8.cloudfront.net/image.jpg In contrast, the following request points to the root URL of the same distribution instead of to a specific object, as in the first example: https://d111111abcdef8.cloudfront.net/ When you define a default root object, an end-user request that calls the root of your distribution returns the default root object. For example, if you designate the file index.html as your default root object, a request for: https://d111111abcdef8.cloudfront.net/ Returns: https://d111111abcdef8.cloudfront.net/index.html Note CloudFront does not determine whether a URL with multiple trailing slashes (https://d111111abcdef8.cloudfront.net///) is equivalent to https:// d111111abcdef8.cloudfront.net/. Your origin server makes that comparison. If you define a default root object, an end-user request for a subdirectory of your distribution does not return the default root object. For example, suppose index.html is your default root object and that CloudFront receives an end-user request for the install directory under your CloudFront distribution: https://d111111abcdef8.cloudfront.net/install/ CloudFront does not return the default root object even if a copy of index.html appears in the install directory. However, if you specified a path to your default root object, (install/ index.html)CloudFront will return the default root object for end-user requests for the install directory How default root object works 342 Amazon CloudFront Developer Guide If you configure your distribution to allow all of the HTTP methods that CloudFront supports, the default root object applies to all methods. For example, if your default root object is index.php and you write your application to submit a POST request to the root of your domain (https:// example.com), CloudFront sends the request to https://example.com/index.php. The behavior of CloudFront default root objects is different from the behavior of Amazon S3 index documents. When you configure an Amazon S3 bucket as a website and specify the index document, Amazon S3 returns the index document even if a user requests a subdirectory in the bucket. (A copy of the index document must appear in every subdirectory.) For more information about configuring Amazon S3 buckets as websites and about index documents, see the Hosting Websites on Amazon S3 chapter in the Amazon Simple Storage Service User Guide. Important Remember that a default root object applies only to your CloudFront distribution. You still need to manage security for your origin. For example, if you are using an Amazon S3 origin, you still need to set your Amazon S3 bucket ACLs appropriately to ensure the level of access you want on your bucket. How CloudFront works if you don’t define a root object If you don't define a default root object, requests for the root of your distribution pass to your origin server. If you are using an Amazon S3 origin, any of the following might be returned: • A list of the contents of your Amazon S3 bucket – Under any of the following conditions, the contents of your origin are visible to anyone who uses CloudFront to access your distribution: • Your bucket is not properly configured. • The Amazon S3 permissions on the bucket associated with your distribution and on the objects in the bucket grant access to everyone. • An end user accesses your origin using your origin root URL. • A list of the private contents of your origin – If you configure your origin as a private distribution (only you and CloudFront have access), the contents of the Amazon S3 bucket associated with your distribution are visible to anyone who has the credentials to access your distribution through CloudFront. In this case, users are not able to access your content through your origin root URL. For more information about distributing private content, see the section called “Restrict content with signed URLs and signed cookies”. How CloudFront works if you don’t define a root object 343 Amazon CloudFront Developer Guide • Error 403 Forbidden—CloudFront returns this error if the permissions on the Amazon S3 bucket associated with your distribution or the permissions on the objects in that bucket deny access to CloudFront and to everyone. Invalidate files to remove content 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 |
AmazonCloudFront_DevGuide-135 | AmazonCloudFront_DevGuide.pdf | 135 | Amazon CloudFront Developer Guide • Error 403 Forbidden—CloudFront returns this error if the permissions on the Amazon S3 bucket associated with your distribution or the permissions on the objects in that bucket deny access to CloudFront and to everyone. Invalidate files to remove content 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 Update existing files using versioned file names. Topics • Choose between invalidating files and using versioned file names • Determine which files to invalidate • What you need to know when invalidating files • Invalidate files • Concurrent invalidation request maximum • Pay for file invalidation Choose between invalidating files and using versioned file names To control the versions of files that are served from your distribution, you can either invalidate files or give them versioned file names. If you want to update your files frequently, we recommend that you primarily use file versioning for the following reasons: • Versioning enables you to control which file a request returns even when the user has a version cached either locally or behind a corporate caching proxy. If you invalidate the file, the user might continue to see the old version until it expires from those caches. • CloudFront access logs include the names of your files, so versioning makes it easier to analyze the results of file changes. • Versioning provides a way to serve different versions of files to different users. Invalidate files to remove content 344 Amazon CloudFront Developer Guide • Versioning simplifies rolling forward and back between file revisions. • Versioning is less expensive. You still have to pay for CloudFront to transfer new versions of your files to edge locations, but you don't have to pay for invalidating files. For more information about file versioning, see Update existing files using versioned file names. Determine which files to invalidate If you want to invalidate multiple files such as all of the files in a directory or all files that begin with the same characters, you can include the * wildcard at the end of the invalidation path. For more information about using the * wildcard, see Invalidation paths. To invalidate files, you can specify either the path for individual files or a path that ends with the * wildcard, which might apply to one file or to many, as shown in the following examples: • /images/image1.jpg • /images/image* • /images/* If you want to invalidate selected files but your users don’t necessarily access every file on your origin, you can determine which files viewers have requested from CloudFront and invalidate only those files. To determine which files viewers have requested, enable CloudFront access logging. For more information about access logs, see Standard logging (access logs). What you need to know when invalidating files When you specify a file to invalidate, refer to the following information: Case sensitivity Invalidation paths are case sensitive. For example, /images/image.jpg and /images/ Image.jpg specify two different files. Changing the URI by using a Lambda function If your CloudFront distribution triggers a Lambda function on viewer request events, and if the function changes the URI of the requested file, we recommend that you invalidate both URIs to remove the file from CloudFront edge caches: • The URI in the viewer request Determine which files to invalidate 345 Amazon CloudFront Developer Guide • The URI after the function changed it Example Example Suppose your Lambda function changes the URI for a file from: https://d111111abcdef8.cloudfront.net/index.html To a URI that includes a language directory: https://d111111abcdef8.cloudfront.net/en/index.html To invalidate the file, you must specify the following paths: • /index.html • /en/index.html For more information, see Invalidation paths. Default root object To invalidate the default root object (file), specify the path the same way that you specify the path for any other file. For more information, see How default root object works. Forwarding cookies If you configured CloudFront to forward cookies to your origin, CloudFront edge caches might contain several versions of the file. When you invalidate a file, CloudFront invalidates every cached version of the file regardless of its associated cookies. You can’t selectively invalidate some versions and not others based on the associated cookies. For more information, see Cache content based on cookies. Forwarding headers If you configured CloudFront to forward a list of headers to your origin and to cache based on the values of the headers, CloudFront edge caches might contain several versions of the file. When you invalidate a file, CloudFront |
AmazonCloudFront_DevGuide-136 | AmazonCloudFront_DevGuide.pdf | 136 | configured CloudFront to forward cookies to your origin, CloudFront edge caches might contain several versions of the file. When you invalidate a file, CloudFront invalidates every cached version of the file regardless of its associated cookies. You can’t selectively invalidate some versions and not others based on the associated cookies. For more information, see Cache content based on cookies. Forwarding headers If you configured CloudFront to forward a list of headers to your origin and to cache based on the values of the headers, CloudFront edge caches might contain several versions of the file. When you invalidate a file, CloudFront invalidates every cached version of the file regardless of the header values. You can’t selectively invalidate some versions and not others based on header values. (If you configure CloudFront to forward all headers to your origin, CloudFront doesn't cache your files.) For more information, see Cache content based on request headers. Forwarding query strings If you configured CloudFront to forward query strings to your origin, you must include the query strings when invalidating files, as shown in the following examples: What you need to know when invalidating files 346 Amazon CloudFront Developer Guide • /images/image.jpg?parameter1=a • /images/image.jpg?parameter1=b If client requests include five different query strings for the same file, you can either invalidate the file five times, once for each query string, or you can use the * wildcard in the invalidation path, as shown in the following example: /images/image.jpg* For more information about using wildcards in the invalidation path, see Invalidation paths. For more information about query strings, see Cache content based on query string parameters. To determine which query strings are in use, you can enable CloudFront logging. For more information, see Standard logging (access logs). Maximum allowed For more information about the maximum number of invalidations allowed, see Concurrent invalidation request maximum. Microsoft Smooth Streaming files You can't invalidate media files in the Microsoft Smooth Streaming format when you have enabled Smooth Streaming for the corresponding cache behavior. Non-ASCII or unsafe characters in the path If the path includes non-ASCII characters or unsafe characters as defined in RFC 1738, URL- encode those characters. Don't URL-encode any other characters in the path, or CloudFront won't invalidate the old version of the updated file. Important Don't use the ~ character in your path. CloudFront doesn't support this character for invalidations, whether it's URL-encoded or not. Invalidation paths The path is relative to the distribution. For example, to invalidate the file at https:// d111111abcdef8.cloudfront.net/images/image2.jpg, you would specify /images/ image2.jpg. What you need to know when invalidating files 347 Amazon CloudFront Note Developer Guide In the CloudFront console, you can omit the leading slash in the path, like this: images/ image2.jpg. When you use the CloudFront API directly, invalidation paths must begin with a leading slash. You can also invalidate multiple files simultaneously by using the * wildcard. The *, which replaces 0 or more characters, must be the last character in the invalidation path. Important To use wildcards (*) in the invalidation, you must put the wildcard at the end of the path. Asterisks (*) inserted anywhere else are treated as a literal character match instead of a wildcard invalidation. If you use the AWS Command Line Interface (AWS CLI) to invalidate files and you specify a path that includes the * wildcard, you must use quotes (") around the path like "/*". The maximum length of a path is 4,000 characters. Example Example: Invalidation paths • To invalidate all files in a directory: /directory-path/* • To invalidate a directory, all of its subdirectories, and all files in the directory and subdirectories: /directory-path* • To invalidate all files that have the same name but different file name extensions, such as logo.jpg, logo.png, and logo.gif: /directory-path/file-name.* • To invalidate all of the files in a directory for which the file name starts with the same characters (such as all of the files for a video in HLS format), regardless of the file name extension: /directory-path/initial-characters-in-file-name* What you need to know when invalidating files 348 Amazon CloudFront Developer Guide • When you configure CloudFront to cache based on query string parameters and you want to invalidate every version of a file: /directory-path/file-name.file-name-extension* • To invalidate all files in a distribution: /* For information about invalidating files if you use a Lambda function to change the URI, see Changing the URI Using a Lambda Function. If the invalidation path is a directory and if you have not standardized on a method for specifying directories—with or without a trailing slash (/)—we recommend that you invalidate the directory both with and without a trailing slash, for example, /images and /images/. Signed URLs If you are using signed URLs, invalidate a file by including only the portion of the URL before the question mark (?). Invalidate |
AmazonCloudFront_DevGuide-137 | AmazonCloudFront_DevGuide.pdf | 137 | • To invalidate all files in a distribution: /* For information about invalidating files if you use a Lambda function to change the URI, see Changing the URI Using a Lambda Function. If the invalidation path is a directory and if you have not standardized on a method for specifying directories—with or without a trailing slash (/)—we recommend that you invalidate the directory both with and without a trailing slash, for example, /images and /images/. Signed URLs If you are using signed URLs, invalidate a file by including only the portion of the URL before the question mark (?). Invalidate files You can use the CloudFront console to create and run an invalidation, display a list of the invalidations that you submitted previously, and display detailed information about an individual invalidation. You can also copy an existing invalidation, edit the list of file paths, and run the edited invalidation. You can't remove invalidations from the list. Contents • Invalidate files • Copy, edit, and rerun an existing invalidation • Cancel invalidations • List invalidations • Display information about an invalidation Invalidate files To invalidate files using the CloudFront console, do the following. Invalidate files 349 Amazon CloudFront Console To invalidate files (console) Developer Guide 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose the distribution for which you want to invalidate files. 3. Choose the Invalidations tab. 4. Choose Create invalidation. 5. For the files that you want to invalidate, enter one invalidation path per line. For information about specifying invalidation paths, see What you need to know when invalidating files. Important Specify file paths carefully. You can’t cancel an invalidation request after you start it. 6. Choose Create invalidation. CloudFront API To learn about invalidating objects and displaying information about invalidations, see the following topics in the Amazon CloudFront API Reference: • CreateInvalidation • ListInvalidations • GetInvalidation Note If you use the AWS Command Line Interface (AWS CLI) to invalidate files and you specify a path that includes the * wildcard, you must use quotes (") around the path, such as the following example: Invalidate files 350 Amazon CloudFront Developer Guide aws cloudfront create-invalidation --distribution-id distribution_ID --paths "/*" Copy, edit, and rerun an existing invalidation You can copy an invalidation that you created previously, update the list of invalidation paths, and run the updated invalidation. You can't copy an existing invalidation, update the invalidation paths, and then save the updated invalidation without running it. Important If you copy an invalidation that is still in progress, update the list of invalidation paths, and then run the updated invalidation, CloudFront won't stop or delete the invalidation that you copied. If any invalidation paths appear in the original and in the copy, CloudFront will try to invalidate the files twice, and both invalidations will count against your maximum number of free invalidations for the month. If you already reached the maximum number of free invalidations, you will be charged for both invalidations of each file. For more information, see Concurrent invalidation request maximum. To copy, edit, and rerun an existing invalidation 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Select the distribution that contains the invalidation that you want to copy. 3. Choose the Invalidations tab. 4. Choose the invalidation that you want to copy. If you aren’t sure which invalidation you want to copy, you can choose an invalidation and choose View details to display detailed information about that invalidation. 5. Choose Copy to new. 6. Update the list of invalidation paths if applicable. 7. Choose Create invalidation. Invalidate files 351 Amazon CloudFront Cancel invalidations Developer Guide When you submit an invalidation request to CloudFront, CloudFront forwards the request to all edge locations within a few seconds, and each edge location starts processing the invalidation immediately. As a result, you can’t cancel an invalidation after you submit it. List invalidations You can display a list of the last 100 invalidations that you’ve created and run for a distribution by using the CloudFront console. If you want to get a list of more than 100 invalidations, use the ListInvalidations API operation. For more information, see ListInvalidations in the Amazon CloudFront API Reference. To list invalidations 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Select the distribution for which you want to display a list of invalidations. 3. Choose the Invalidations tab. Note You can’t remove invalidations from the list. Display information about an invalidation You can display detailed information about an invalidation, including distribution ID, invalidation ID, the status of the invalidation, the date and time that the invalidation was created, and a complete list of the invalidation paths. To display information about an invalidation |
AmazonCloudFront_DevGuide-138 | AmazonCloudFront_DevGuide.pdf | 138 | see ListInvalidations in the Amazon CloudFront API Reference. To list invalidations 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Select the distribution for which you want to display a list of invalidations. 3. Choose the Invalidations tab. Note You can’t remove invalidations from the list. Display information about an invalidation You can display detailed information about an invalidation, including distribution ID, invalidation ID, the status of the invalidation, the date and time that the invalidation was created, and a complete list of the invalidation paths. To display information about an invalidation 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Select the distribution that contains the invalidation that you want to display detailed information for. 3. Choose the Invalidations tab. Invalidate files 352 Amazon CloudFront Developer Guide 4. Choose the applicable invalidation ID or select the invalidation ID and then choose View details. Concurrent invalidation request maximum If you’re invalidating files individually, you can have invalidation requests for up to 3,000 files per distribution in progress at one time. This can be one invalidation request for up to 3,000 files, up to 3,000 requests for one file each, or any other combination that doesn’t exceed 3,000 files. For example, you can submit 30 invalidation requests that invalidate 100 files each. As long as all 30 invalidation requests are still in progress, you can’t submit any more invalidation requests. If you exceed the maximum, CloudFront returns an error message. If you’re using the * wildcard, you can have requests for up to 15 invalidation paths in progress at one time. You can also have invalidation requests for up to 3,000 individual files per distribution in progress at the same time; the maximum on wildcard invalidation requests allowed is independent of the maximum on invalidating files individually. Pay for file invalidation The first 1,000 invalidation paths that you submit per month are free; you pay for each invalidation path over 1,000 in a month. An invalidation path can be for a single file (such as /images/ logo.jpg) or for multiple files (such as /images/*). A path that includes the * wildcard counts as one path even if it causes CloudFront to invalidate thousands of files. The maximum of 1,000 free invalidation paths per month applies to the total number of invalidation paths across all of the distributions that you create with one AWS account. For example, if you use the AWS account john@example.com to create three distributions, and you submit 600 invalidation paths for each distribution in a given month (for a total of 1,800 invalidation paths), AWS will charge you for the difference between the total invalidation paths and the 1000 free limit. In this example, AWS would charge you for 800 invalidation paths in that month. The charge to submit an invalidation path is the same regardless of the number of files you’re invalidating: a single file (/images/logo.jpg) or all of the files that are associated with a distribution (/*). Because you're charged per path in your invalidation request, even if you bundle multiple paths into a single request, each path is still counted individually for billing purposes. For more information about invalidation pricing, see Amazon CloudFront Pricing. For more information about invalidation paths, see Invalidation paths. Concurrent invalidation request maximum 353 Amazon CloudFront Developer Guide Serve compressed files When requested objects are compressed, downloads can be faster because the objects are smaller —in some cases, less than a quarter the size of the original. Faster downloads can result in faster rendering of webpages for your viewers, especially for JavaScript and CSS files. In addition, the cost of CloudFront data transfer is based on the total amount of data served. Serving compressed objects can be less expensive than serving them uncompressed. Topics • Configure CloudFront to compress objects • How CloudFront compression works • When CloudFront compresses objects • File types that CloudFront compresses • ETag header conversion Configure CloudFront to compress objects To configure CloudFront to compress objects, update the cache behavior that you want to serve the compressed objects. To configure CloudFront to compress objects (console) 1. Sign in to the CloudFront console. 2. Choose your distribution and then choose the Behavior to edit. 3. For the Compress objects automatically setting, choose Yes. 4. Use a cache policy to specify the caching settings, and enable both Gzip and Brotli compression formats. 5. Set the TTL settings in the cache policy to a value greater than zero. If you set the Minimum TTL value to zero, CloudFront won't cache compressed content. Notes • You must use cache policies to use Brotli compression. Brotli doesn't support legacy cache settings. Serve compressed files 354 Amazon CloudFront Developer Guide • To enable compression by using |
AmazonCloudFront_DevGuide-139 | AmazonCloudFront_DevGuide.pdf | 139 | CloudFront console. 2. Choose your distribution and then choose the Behavior to edit. 3. For the Compress objects automatically setting, choose Yes. 4. Use a cache policy to specify the caching settings, and enable both Gzip and Brotli compression formats. 5. Set the TTL settings in the cache policy to a value greater than zero. If you set the Minimum TTL value to zero, CloudFront won't cache compressed content. Notes • You must use cache policies to use Brotli compression. Brotli doesn't support legacy cache settings. Serve compressed files 354 Amazon CloudFront Developer Guide • To enable compression by using AWS CloudFormation or the CloudFront API, set the Compress, EnableAcceptEncodingGzip, EnableAcceptEncodingBrotli parameters to true. To understand how CloudFront compresses objects, see the following section. How CloudFront compression works 1. A viewer requests an object. The viewer includes the Accept-Encoding HTTP header in the request, and the header value includes gzip, br, or both. This indicates that the viewer supports compressed objects. When the viewer supports both Gzip and Brotli, CloudFront uses Brotli. Note Chrome and Firefox web browsers support Brotli compression only when the request is sent using HTTPS. They don't support Brotli with HTTP requests. 2. At the edge location, CloudFront checks the cache for a compressed copy of the requested object. 3. Depending whether the compressed object is in the cache or not, CloudFront does one of the following: • • If the compressed object is already in the cache, CloudFront sends the object to the viewer and skips the remaining steps. If the compressed object isn't in the cache, CloudFront forwards the request to the origin. Note If an uncompressed copy of the object is already in the cache, CloudFront might send it to the viewer without forwarding the request to the origin. For example, this can happen when CloudFront previously skipped compression. When this happens, CloudFront caches the uncompressed object and continues to serve it until the object expires, is evicted, or is invalidated. How CloudFront compression works 355 Amazon CloudFront Developer Guide 4. 5. 6. If the origin returns a compressed object, (as indicated by the Content-Encoding header in the HTTP response), CloudFront sends the compressed object to the viewer, adds it to the cache, and skips the remaining steps. CloudFront doesn’t compress the object again. If the origin returns an uncompressed object to CloudFront without the Content-Encoding header in the HTTP response, CloudFront then determines whether the object can be compressed. For more information, see When CloudFront compresses objects. If the object can be compressed, CloudFront compresses it, sends it to the viewer, and then adds it to the cache. 7. If there are subsequent viewer requests for the same object, CloudFront returns the first cached version. For example, if a viewer requests a specific cached object that uses Gzip compression, and the viewer accepts the Gzip format, subsequent requests to the same object will always return the Gzip version, even if the viewer accepts both Brotli and Gzip. Some custom origins can also compress objects. Your origin might be able to compress objects that CloudFront doesn’t compress. For more information, see File types that CloudFront compresses. When CloudFront compresses objects The following list provides more information about when CloudFront compresses objects. Request uses HTTP 1.0 If a request to CloudFront uses HTTP 1.0, CloudFront removes the Accept-Encoding header and doesn't compress the object in the response. Accept-Encoding request header If the Accept-Encoding header is missing from the viewer request, or if it doesn’t contain gzip or br as a value, CloudFront doesn't compress the object in the response. If the Accept- Encoding header includes additional values such as deflate, CloudFront removes them before forwarding the request to the origin. When CloudFront is configured to compress objects, it includes the Accept-Encoding header in the cache key and in origin requests automatically. Content is already cached when you configure CloudFront to compress objects CloudFront compresses objects when it gets them from the origin. When you configure CloudFront to compress objects, CloudFront doesn’t compress objects that are already cached in edge locations. In addition, when a cached object expires in an edge location and CloudFront When CloudFront compresses objects 356 Amazon CloudFront Developer Guide forwards another request for the object to your origin, CloudFront doesn’t compress the object when your origin returns an HTTP status code 304. This means that the edge location already has the latest version of the object. If you want CloudFront to compress objects that are already cached in edge locations, you need to invalidate those objects. For more information, see Invalidate files to remove content. Origin is already configured to compress objects If you configure CloudFront to compress objects and the origin also compresses objects, the origin should include a Content-Encoding header. This header indicates to CloudFront that the object is |
AmazonCloudFront_DevGuide-140 | AmazonCloudFront_DevGuide.pdf | 140 | request for the object to your origin, CloudFront doesn’t compress the object when your origin returns an HTTP status code 304. This means that the edge location already has the latest version of the object. If you want CloudFront to compress objects that are already cached in edge locations, you need to invalidate those objects. For more information, see Invalidate files to remove content. Origin is already configured to compress objects If you configure CloudFront to compress objects and the origin also compresses objects, the origin should include a Content-Encoding header. This header indicates to CloudFront that the object is already compressed. When a response from an origin includes the Content- Encoding header, CloudFront doesn't compress the object, regardless of the header’s value. CloudFront sends the response to the viewer and caches the object in the edge location. File types that CloudFront compresses For a complete list, see File types that CloudFront compresses. Size of objects that CloudFront compresses CloudFront compresses objects that are between 1,000 bytes and 10,000,000 bytes in size. Content-Length header The origin must include a Content-Length header in the response, which CloudFront uses to determine whether the size of the object is in the range that CloudFront compresses. If the Content-Length header is missing, contains an invalid value, or contains a value outside the range of sizes that CloudFront compresses, CloudFront doesn't compress the object. For more information about how CloudFront processes large objects that can exceed the size range, see How CloudFront processes partial requests for an object (range GETs). HTTP status code of the response CloudFront compresses objects only when the HTTP status code of the response is 200, 403, or 404. Response has no body When the HTTP response from the origin has no body, there is nothing for CloudFront to compress. ETag header CloudFront sometimes modifies the ETag header in the HTTP response when it compresses objects. For more information, see the section called “ETag header conversion”. When CloudFront compresses objects 357 Amazon CloudFront CloudFront skips compression Developer Guide CloudFront compresses objects on a best-effort basis. In rare cases, CloudFront skips compressing an object when CloudFront experiences high traffic load. CloudFront makes this decision based on a variety of factors, including host capacity. If CloudFront skips compression for an object, it caches the uncompressed object and continues to serve it to viewers until the object expires, is evicted, or is invalidated. File types that CloudFront compresses If you configure CloudFront to compress objects, CloudFront only compresses objects that have one of the following values in the Content-Type response header: • application/dash+xml • application/eot • application/font • application/font-sfnt • application/javascript • application/json • application/opentype • application/otf • application/pdf • application/pkcs7-mime • application/protobuf • application/rss+xml • application/truetype • application/ttf • application/vnd.apple.mpegurl • application/vnd.mapbox-vector-tile • application/vnd.ms-fontobject • application/wasm • application/xhtml+xml File types that CloudFront compresses 358 Developer Guide Amazon CloudFront • application/xml • application/x-font-opentype • application/x-font-truetype • application/x-font-ttf • application/x-httpd-cgi • application/x-javascript • application/x-mpegurl • application/x-opentype • application/x-otf • application/x-perl • application/x-ttf • font/eot • font/opentype • font/otf • font/ttf • image/svg+xml • text/css • text/csv • text/html • text/javascript • text/js • text/plain • text/richtext • text/tab-separated-values • text/xml • text/x-component • text/x-java-source • text/x-script • vnd.apple.mpegurl File types that CloudFront compresses 359 Amazon CloudFront Developer Guide ETag header conversion When the uncompressed object from the origin includes a valid, strong ETag HTTP header, and CloudFront compresses the object, CloudFront also converts the strong ETag header value to a weak ETag, and returns the weak ETag value to the viewer. Viewers can store the weak ETag value and use it to send conditional requests with the If-None-Match HTTP header. This allows viewers, CloudFront, and the origin to treat the compressed and uncompressed versions of an object as semantically equivalent, which reduces unnecessary data transfer. A valid, strong ETag header value begins and ends with a double quote character ("). To convert the strong ETag value to a weak one, CloudFront adds the characters W/ to the beginning of the strong ETag value. When the object from the origin includes a weak ETag header value (a value that begins with the characters W/), CloudFront does not modify this value, and returns it to the viewer as received from the origin. When the object from the origin includes an invalid ETag header value (the value does not begin with " or with W/), CloudFront removes the ETag header and returns the object to the viewer without the ETag response header. For more information, see the following pages in the MDN web docs: • Directives (ETag HTTP header) • Weak validation (HTTP conditional requests) • If-None-Match HTTP header ETag header conversion 360 Amazon CloudFront Developer Guide Use AWS WAF protections You can use AWS WAF to protect your CloudFront distributions and origin servers. AWS WAF is a |
AmazonCloudFront_DevGuide-141 | AmazonCloudFront_DevGuide.pdf | 141 | as received from the origin. When the object from the origin includes an invalid ETag header value (the value does not begin with " or with W/), CloudFront removes the ETag header and returns the object to the viewer without the ETag response header. For more information, see the following pages in the MDN web docs: • Directives (ETag HTTP header) • Weak validation (HTTP conditional requests) • If-None-Match HTTP header ETag header conversion 360 Amazon CloudFront Developer Guide Use AWS WAF protections You can use AWS WAF to protect your CloudFront distributions and origin servers. AWS WAF is a web application firewall that helps secure your web applications and APIs by blocking requests before they reach your servers. For more information, see Accelerate and protect your websites using CloudFront and AWS WAF and Guidelines for Implementing AWS WAF. To enable AWS WAF protections, you can: • Use one-click protection in the CloudFront console. One-click protection creates an AWS WAF web access control list (web ACL), configures rules to protect your servers from common web threats, and attaches the web ACL to the CloudFront distribution for you. The topics in this section assume the use of one-click protections. • Use a preconfigured web ACL (access control list) that you create in the AWS WAF console, or by using the AWS WAF APIs. For more information, see Web access control lists (ACLs) in the AWS WAF Developer Guide and AssociateWebACL in the AWS WAF API Reference You can enable AWS WAF when you: • Create a distribution • Use the Security dashboard to edit the security settings of an existing distribution When you use one-click protection, CloudFront applies an AWS recommended set of protections that: • Block IP addresses from potential threats based on Amazon internal threat intelligence. • Protect against the most common vulnerabilities found in web applications as described in the OWASP Top 10. • Defend against malicious actors discovering application vulnerabilities. Important You must enable AWS WAF if you want to view security metrics in the CloudFront Security dashboard. Without AWS WAF, enabled, you can only use the Security dashboard to enable AWS WAF or configure CloudFront geographic restrictions. For more information about 361 Amazon CloudFront Developer Guide the dashboard, see Manage AWS WAF security protections in the CloudFront security dashboard, later in this section. Topics • Enable AWS WAF for distributions • Manage AWS WAF security protections in the CloudFront security dashboard • Set up rate limiting • Disable AWS WAF security protections Enable AWS WAF for distributions You can enable AWS WAF when you create a distribution, or you can enable security protections for an existing access control list (ACL). If you enable AWS WAF for your CloudFront distribution, you can also enable bot control and configure security protection by bot category. Topics • Enable AWS WAF for a new distribution • Use an existing web ACL • Enable bot control • Configure protection by bot category Enable AWS WAF for a new distribution The following procedure shows you how to enable AWS WAF when you create a new CloudFront distribution. To enable AWS WAF for a new distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions, and then choose Create distribution. 3. As needed, follow the steps in Create a distribution. Enable AWS WAF for distributions 362 Amazon CloudFront Developer Guide 4. In the Web Application Firewall section, choose Edit, then choose Enable security protections. 5. Complete the following fields: • Use monitor mode – You enable monitor mode when you want to first collect data to test how protection will work. When you enable monitor mode, requests aren't blocked if the protections were active. Instead, monitor mode collects data about requests that would be blocked if the protections were active. When you're ready to begin blocking, you can enable blocking on the Security page. • Additional protections – Choose any options that you want to enable. If you enable rate limiting, see the section called “Set up rate limiting” for more information. • Price estimate – You can open the section to display a field where you enter a different number of requests/month and see a new estimate. 6. Review the remaining distribution settings, then choose Create distribution. After you create a distribution, CloudFront creates a Security dashboard. You can use this dashboard to disable or enable AWS WAF. If you haven't enabled AWS WAF yet, the charts and graphs in the dashboard remain blank. Use an existing web ACL If you have an existing web ACL, you can use it instead of the protection offered by AWS WAF. To use an existing AWS WAF configuration 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Do one of the following: a. Choose Create distribution and follow the steps in |
AmazonCloudFront_DevGuide-142 | AmazonCloudFront_DevGuide.pdf | 142 | 6. Review the remaining distribution settings, then choose Create distribution. After you create a distribution, CloudFront creates a Security dashboard. You can use this dashboard to disable or enable AWS WAF. If you haven't enabled AWS WAF yet, the charts and graphs in the dashboard remain blank. Use an existing web ACL If you have an existing web ACL, you can use it instead of the protection offered by AWS WAF. To use an existing AWS WAF configuration 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Do one of the following: a. Choose Create distribution and follow the steps in Create a distribution, then return to this topic. b. Choose an existing configuration, and then choose the Security tab. 3. In the Web Application Firewall (WAF) section, choose Edit, then Enable security protections. 4. Choose Use existing WAF configuration. This option appears only if you have web ACLs configured. 5. Choose your existing web ACL from the Choose a web ACL table. Use an existing web ACL 363 Amazon CloudFront Developer Guide 6. Review the remaining distribution settings, and then choose Create distribution. Enable bot control If you enable AWS WAF for your CloudFront distribution, you can view bot requests for a given time range under the security dashboard in the CloudFront console. You can also enable or disable bot control here. You incur charges when you enable bot control. The security dashboard provides a cost estimate. If you enable bot control, the security dashboard displays bot traffic by each bot type and category. If you disable bot control, bot traffic is displayed based on request sampling. To enable bot control 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions, then choose the distribution that you want to change. 3. Choose the Security tab. 4. 5. Scroll down to the Bot requests for a given time range section and choose Enable Bot Control. In the Bot Control dialog box, under Configuration, select the Enable Bot Control for common bots check box. 6. Choose Save changes. Configure protection by bot category When you enable bot control, you can configure how each unverified bot is handled per bot category. For example, you can set an HTTP library bot to Monitor mode and assign a Challenge to a link checker. Note Bots that are known by AWS to be common and verifiable, such as known search engine crawlers, aren't subject to the actions you set here. Bot control confirms that validated bots come from the source that they claim before marking them as verified. Enable bot control 364 Amazon CloudFront Developer Guide To configure protection for a bot category 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions, then choose the distribution that you want to change. 3. Choose the Security tab. 4. In the Requests by bot category chart, point to any of the items in the Unverified bot action column and choose the pencil icon to edit it. 5. Open the resulting list and choose one of the following: • Block • Allow • Monitor mode • CAPTCHA • Challenge 6. Select the check mark next to the list to save your change. Manage AWS WAF security protections in the CloudFront security dashboard CloudFront creates a security dashboard for each of your distributions. You use the dashboards in the CloudFront console. With the dashboards, you can use CloudFront and AWS WAF together in a single location to monitor and manage common security protections for your web applications. The dashboards provide the following tasks and data: • Security configuration – You can enable and disable AWS WAF protections, and see any app- specific protections such as WordPress protections. • Security trends – These include allowed and blocked requests, challenge and CAPTCHA requests, and top attack types. You can see traffic ratios and how they change over time. For example, if all requests increase by 3% but allowed requests increase by 14%, that means you allowed a larger portion of your traffic through in the current period. • Bot requests – You can see how much traffic comes from bots, which types of bots (verified vs non-verified), and how the percentage allocations of bot types (verified vs non-verified) change over time. For more information about enabling bot control, see Enable bot control. Manage AWS WAF security protections for CloudFront 365 Amazon CloudFront Developer Guide • Request logs – Log data can help answer questions about security trends or bot requests. You can search your logs without writing queries, and view aggregate charts to help determine if a filtered set of logs is primarily being driven by a subset of HTTP methods, IP addresses, URI paths, or countries. You can hover over values in the charts and block IP addresses and countries. For more |
AmazonCloudFront_DevGuide-143 | AmazonCloudFront_DevGuide.pdf | 143 | bot types (verified vs non-verified) change over time. For more information about enabling bot control, see Enable bot control. Manage AWS WAF security protections for CloudFront 365 Amazon CloudFront Developer Guide • Request logs – Log data can help answer questions about security trends or bot requests. You can search your logs without writing queries, and view aggregate charts to help determine if a filtered set of logs is primarily being driven by a subset of HTTP methods, IP addresses, URI paths, or countries. You can hover over values in the charts and block IP addresses and countries. For more information, see Enable AWS WAF logs. • Geographic restriction management – CloudFront and AWS WAF provide geographic restriction features. CloudFront provides geographic restrictions for free, but metrics for CloudFront geographic restrictions aren't displayed in the security dashboard. To see request metrics for blocked country requests, you must use AWS WAF geographic restrictions. To do this, hover over a country bar in the security dashboard and block the country. For more information, see Use CloudFront geographic restrictions. • The Block option might not be available if you previously created a custom AWS WAF rule outside of the CloudFront console to block countries. Topics • Prerequisites • Enable AWS WAF logs Prerequisites You must enable AWS WAF if you want to view security metrics in the CloudFront Security dashboard. If you don't enable AWS WAF, you can only use the Security dashboard to enable AWS WAF or configure CloudFront geographic restrictions. For more information about enabling AWS WAF, see Enable AWS WAF for distributions. Enable AWS WAF logs AWS WAF log data can help you isolate specific traffic patterns. For example, logs can show you where certain traffic comes from or what it does. If you enable AWS WAF logging to CloudWatch, the CloudFront security dashboard queries, aggregates, and displays insights from the CloudWatch logs. We don’t charge to use the security dashboard, but CloudWatch pricing applies to logs queried through the dashboard. For more information, see Amazon CloudWatch Pricing. Prerequisites 366 Amazon CloudFront To enable logs Developer Guide 1. Enter your expected request volume in the Number of requests/month box to estimate the costs of enabling logs. 2. Select the Enable AWS WAF logs check box. 3. Choose Enable. CloudFront creates a CloudWatch logs group and updates your AWS WAF configuration to begin logging to CloudWatch. On first use, log data can take several minutes to appear. The Requests section of the chart lists each request. Below the individual requests, the bar charts aggregate data by HTTP method, top URI paths, top IP addresses, and top countries. The charts can help you find patterns. For example, you may see a disproportionate volume of requests from a single IP address, or data from a country that you haven't previously seen in your logs. You can filter requests based on Country, Host Header, and other attributes to help find unwanted traffic. Once you identify that traffic, hover over an individual request or chart item and block an IP address or country. Note Displayed metrics are based on web ACL. Therefore, if you associate the same web ACL to multiple distributions, you will see all metrics for your web ACL, not only the AWS WAF requests that are processed for that distribution. Set up rate limiting Rate limiting is one of the recommendations you may receive when configuring security protections. CloudFront always enables rate limiting in monitor mode. When monitor mode is enabled, CloudFront captures metrics that tell you if the rate you configured in the Rate limiting field has been exceeded, how often, and by how much. After you save the distribution, CloudFront starts to collect data based on the number in the Rate limiting field. You can enable or manage the rate limiting settings in the Security - Web Application Firewall (WAF) section on the Security tab of any CloudFront distribution. Set up rate limiting 367 Amazon CloudFront Note Developer Guide The Rate limiting option only appears in the CloudFront console if you specified a non- S3 custom origin for your distribution. Otherwise, you will only see the Core protections enabled for the distribution. For more information about origin types, see Use various origins with CloudFront distributions. To set up rate limiting 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions, and then choose the distribution that you want to change. 3. Choose the Security tab. 4. In the Security – Web Application Firewall (WAF) section, choose Edit. 5. Under Additional protections, select Rate limiting. You can optionally change the rate limit. When you have fine-tuned the rate, choose Save changes. 6. In the Security – Web Application Firewall (WAF) section, next to Rate limiting, you can choose Monitor mode and then choose Enable blocking to deactivate |
AmazonCloudFront_DevGuide-144 | AmazonCloudFront_DevGuide.pdf | 144 | various origins with CloudFront distributions. To set up rate limiting 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions, and then choose the distribution that you want to change. 3. Choose the Security tab. 4. In the Security – Web Application Firewall (WAF) section, choose Edit. 5. Under Additional protections, select Rate limiting. You can optionally change the rate limit. When you have fine-tuned the rate, choose Save changes. 6. In the Security – Web Application Firewall (WAF) section, next to Rate limiting, you can choose Monitor mode and then choose Enable blocking to deactivate monitor mode. CloudFront will start to block requests that exceed the specified rate limit. For more information about enabling AWS WAF and rate limiting, see the Introducing CloudFront Security Dashboard, a Unified CDN and Security Experience blog post. Disable AWS WAF security protections If your distribution doesn't need AWS WAF security protections, you can disable this feature by using the CloudFront console. If you previously enabled AWS WAF protection and didn't choose an existing WAF configuration (also known as one-click protection), CloudFront automatically created a web ACL for you. For web ACLs created this way, the CloudFront console will disassociate the resource and delete the web ACL. Disassociating a web ACL is different from deleting it. Disassociating removes the web ACL from your distribution, but it's not deleted from your AWS account. For more information, see Disable AWS WAF security protections 368 Amazon CloudFront Developer Guide Associating or disassociating a web ACL with an AWS resource in the AWS WAF, AWS Firewall Manager, and AWS Shield Advanced Developer Guide. See the following procedure to disable AWS WAF protections and disassociate the web ACL from your distribution. To disable AWS WAF security protections in CloudFront 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions, and then choose the distribution that you want to change. 3. Choose the Security tab and then choose Edit. 4. In the Web Application Firewall (WAF) section, choose Disable AWS WAF protection. 5. Choose Save changes. Notes • If you disabled AWS WAF security protection and you still want to delete the web ACL from your AWS account, you can delete it manually. Follow the procedure to delete a web ACL. In the AWS WAF & Shield console, for the Web ACLs page, you must choose the Global (CloudFront) list to find the web ACLs. • When you delete a distribution from the CloudFront console, CloudFront will attempt to also delete the web ACL if you chose one-click protection. This is best effort and isn't always guaranteed. For more information, see Delete a distribution. Disable AWS WAF security protections 369 Amazon CloudFront Developer Guide Configure secure access and restrict access to content CloudFront provides several options for securing content that it delivers. The following are some ways you can use CloudFront to secure and restrict access to content: • Configure HTTPS connections • Prevent users in specific geographic locations from accessing content • Require users to access content using CloudFront signed URLs or signed cookies • Set up field-level encryption for specific content fields • Use AWS WAF to control access to your content You should also implement a DDoS-resilient architecture for your infrastructure and applications. For more information, see AWS Best Practices for DDoS Resiliency. For additional information, see the following: • Securing your content delivery with CloudFront • SIEM on Amazon OpenSearch Service Topics • Use HTTPS with CloudFront • Use alternate domain names and HTTPS • Serve private content with signed URLs and signed cookies • Restrict access to an AWS origin • Restrict access to Application Load Balancers • Restrict the geographic distribution of your content • Use field-level encryption to help protect sensitive data Use HTTPS with CloudFront You can configure CloudFront to require that viewers use HTTPS so that connections are encrypted when CloudFront communicates with viewers. You also can configure CloudFront to use HTTPS Use HTTPS with CloudFront 370 Amazon CloudFront Developer Guide with your origin so that connections are encrypted when CloudFront communicates with your origin. If you configure CloudFront to require HTTPS both to communicate with viewers and to communicate with your origin, here’s what happens when CloudFront receives a request: 1. A viewer submits an HTTPS request to CloudFront. There’s some SSL/TLS negotiation here between the viewer and CloudFront. In the end, the viewer submits the request in an encrypted format. 2. If the CloudFront edge location contains a cached response, CloudFront encrypts the response and returns it to the viewer, and the viewer decrypts it. 3. If the CloudFront edge location doesn’t contain a cached response, CloudFront performs SSL/ TLS negotiation with your origin and, when the negotiation is complete, forwards the request to your origin in an encrypted format. 4. |
AmazonCloudFront_DevGuide-145 | AmazonCloudFront_DevGuide.pdf | 145 | here’s what happens when CloudFront receives a request: 1. A viewer submits an HTTPS request to CloudFront. There’s some SSL/TLS negotiation here between the viewer and CloudFront. In the end, the viewer submits the request in an encrypted format. 2. If the CloudFront edge location contains a cached response, CloudFront encrypts the response and returns it to the viewer, and the viewer decrypts it. 3. If the CloudFront edge location doesn’t contain a cached response, CloudFront performs SSL/ TLS negotiation with your origin and, when the negotiation is complete, forwards the request to your origin in an encrypted format. 4. Your origin decrypts the request, processes it (generates a response), encrypts the response, and returns the response to CloudFront. 5. CloudFront decrypts the response, re-encrypts it, and forwards it to the viewer. CloudFront also caches the response in the edge location so that it’s available the next time it’s requested. 6. The viewer decrypts the response. The process works basically the same way whether your origin is an Amazon S3 bucket, MediaStore, or a custom origin such as an HTTP/S server. Note To help thwart SSL renegotiation-type attacks, CloudFront does not support renegotiation for viewer and origin requests. For information about how to require HTTPS between viewers and CloudFront, and between CloudFront and your origin, see the following topics. Topics • Require HTTPS for communication between viewers and CloudFront • Require HTTPS for communication between CloudFront and your custom origin • Require HTTPS for communication between CloudFront and your Amazon S3 origin Use HTTPS with CloudFront 371 Amazon CloudFront Developer Guide • Supported protocols and ciphers between viewers and CloudFront • Supported protocols and ciphers between CloudFront and the origin Require HTTPS for communication between viewers and CloudFront You can configure one or more cache behaviors in your CloudFront distribution to require HTTPS for communication between viewers and CloudFront. You also can configure one or more cache behaviors to allow both HTTP and HTTPS, so that CloudFront requires HTTPS for some objects but not for others. The configuration steps depend on which domain name you're using in object URLs: • If you're using the domain name that CloudFront assigned to your distribution, such as d111111abcdef8.cloudfront.net, you change the Viewer Protocol Policy setting for one or more cache behaviors to require HTTPS communication. In that configuration, CloudFront provides the SSL/TLS certificate. To change the value of Viewer Protocol Policy by using the CloudFront console, see the procedure later in this section. For information about how to use the CloudFront API to change the value of the ViewerProtocolPolicy element, see UpdateDistribution in the Amazon CloudFront API Reference. • If you're using your own domain name, such as example.com, you need to change several CloudFront settings. You also need to use an SSL/TLS certificate provided by AWS Certificate Manager (ACM), or import a certificate from a third-party certificate authority into ACM or the IAM certificate store. For more information, see Use alternate domain names and HTTPS. Note If you want to ensure that the objects that viewers get from CloudFront were encrypted when CloudFront got them from your origin, always use HTTPS between CloudFront and your origin. If you recently changed from HTTP to HTTPS between CloudFront and your origin, we recommend that you invalidate objects in CloudFront edge locations. CloudFront will return an object to a viewer regardless of whether the protocol used by the viewer (HTTP or HTTPS) matches the protocol that CloudFront used to get the object. For more information about removing or replacing objects in a distribution, see Add, remove, or replace content that CloudFront distributes. Require HTTPS between viewers and CloudFront 372 Amazon CloudFront Developer Guide Require HTTPS for viewers To require HTTPS between viewers and CloudFront for one or more cache behaviors, perform the following procedure. To configure CloudFront to require HTTPS between viewers and CloudFront 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the top pane of the CloudFront console, choose the ID for the distribution that you want to update. 3. On the Behaviors tab, select the cache behavior that you want to update, and then choose Edit. 4. Specify one of the following values for Viewer protocol policy: Redirect HTTP to HTTPS Viewers can use both protocols. HTTP GET and HEAD requests are automatically redirected to HTTPS requests. CloudFront returns HTTP status code 301 (Moved Permanently) along with the new HTTPS URL. The viewer then resubmits the request to CloudFront using the HTTPS URL. Important If you send POST, PUT, DELETE, OPTIONS, or PATCH over HTTP with an HTTP to HTTPS cache behavior and a request protocol version of HTTP 1.1 or above, CloudFront redirects the request to a HTTPS location with a HTTP status code 307 (Temporary Redirect). This guarantees that the request |
AmazonCloudFront_DevGuide-146 | AmazonCloudFront_DevGuide.pdf | 146 | for Viewer protocol policy: Redirect HTTP to HTTPS Viewers can use both protocols. HTTP GET and HEAD requests are automatically redirected to HTTPS requests. CloudFront returns HTTP status code 301 (Moved Permanently) along with the new HTTPS URL. The viewer then resubmits the request to CloudFront using the HTTPS URL. Important If you send POST, PUT, DELETE, OPTIONS, or PATCH over HTTP with an HTTP to HTTPS cache behavior and a request protocol version of HTTP 1.1 or above, CloudFront redirects the request to a HTTPS location with a HTTP status code 307 (Temporary Redirect). This guarantees that the request is sent again to the new location using the same method and body payload. If you send POST, PUT, DELETE, OPTIONS, or PATCH requests over HTTP to HTTPS cache behavior with a request protocol version below HTTP 1.1, CloudFront returns a HTTP status code 403 (Forbidden). When a viewer makes an HTTP request that is redirected to an HTTPS request, CloudFront charges for both requests. For the HTTP request, the charge is only for the request and for the headers that CloudFront returns to the viewer. For the HTTPS request, the charge is for the request, and for the headers and the object that are returned by your origin. Require HTTPS between viewers and CloudFront 373 Amazon CloudFront HTTPS only Developer Guide Viewers can access your content only if they're using HTTPS. If a viewer sends an HTTP request instead of an HTTPS request, CloudFront returns HTTP status code 403 (Forbidden) and does not return the object. 5. Choose Save changes. 6. Repeat steps 3 through 5 for each additional cache behavior that you want to require HTTPS for between viewers and CloudFront. 7. Confirm the following before you use the updated configuration in a production environment: • The path pattern in each cache behavior applies only to the requests that you want viewers to use HTTPS for. • The cache behaviors are listed in the order that you want CloudFront to evaluate them in. For more information, see Path pattern. • The cache behaviors are routing requests to the correct origins. Require HTTPS for communication between CloudFront and your custom origin You can require HTTPS for communication between CloudFront and your origin. Note If your origin is an Amazon S3 bucket that’s configured as a website endpoint, you can’t configure CloudFront to use HTTPS with your origin because Amazon S3 doesn’t support HTTPS for website endpoints. To require HTTPS between CloudFront and your origin, follow the procedures in this topic to do the following: 1. In your distribution, change the Origin Protocol Policy setting for the origin. 2. Install an SSL/TLS certificate on your origin server (this isn’t required when you use an Amazon S3 origin or certain other AWS origins). Topics Require HTTPS to a custom origin 374 Amazon CloudFront Developer Guide • Require HTTPS for custom origins • Install an SSL/TLS certificate on your custom origin Require HTTPS for custom origins The following procedure explains how to configure CloudFront to use HTTPS to communicate with an Elastic Load Balancing load balancer, an Amazon EC2 instance, or another custom origin. For information about using the CloudFront API to update a distribution, see UpdateDistribution in the Amazon CloudFront API Reference. To configure CloudFront to require HTTPS between CloudFront and your custom origin 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the top pane of the CloudFront console, choose the ID for the distribution that you want to update. 3. On the Behaviors tab, select the origin that you want to update, and then choose Edit. 4. Update the following settings: Origin Protocol Policy Change the Origin Protocol Policy for the applicable origins in your distribution: • HTTPS Only – CloudFront uses only HTTPS to communicate with your custom origin. • Match Viewer – CloudFront communicates with your custom origin using HTTP or HTTPS, depending on the protocol of the viewer request. For example, if you choose Match Viewer for Origin Protocol Policy and the viewer uses HTTPS to request an object from CloudFront, CloudFront also uses HTTPS to forward the request to your origin. Choose Match Viewer only if you specify Redirect HTTP to HTTPS or HTTPS Only for Viewer Protocol Policy. CloudFront caches the object only once even if viewers make requests using both HTTP and HTTPS protocols. Origin SSL Protocols Choose the Origin SSL Protocols for the applicable origins in your distribution. The SSLv3 protocol is less secure, so we recommend that you choose SSLv3 only if your origin doesn’t Require HTTPS to a custom origin 375 Amazon CloudFront Developer Guide support TLSv1 or later. The TLSv1 handshake is both backwards and forwards compatible with SSLv3, but TLSv1.1 and later are not. When you choose SSLv3, CloudFront |
AmazonCloudFront_DevGuide-147 | AmazonCloudFront_DevGuide.pdf | 147 | you specify Redirect HTTP to HTTPS or HTTPS Only for Viewer Protocol Policy. CloudFront caches the object only once even if viewers make requests using both HTTP and HTTPS protocols. Origin SSL Protocols Choose the Origin SSL Protocols for the applicable origins in your distribution. The SSLv3 protocol is less secure, so we recommend that you choose SSLv3 only if your origin doesn’t Require HTTPS to a custom origin 375 Amazon CloudFront Developer Guide support TLSv1 or later. The TLSv1 handshake is both backwards and forwards compatible with SSLv3, but TLSv1.1 and later are not. When you choose SSLv3, CloudFront only sends SSLv3 handshake requests. 5. Choose Save changes. 6. Repeat steps 3 through 5 for each additional origin that you want to require HTTPS for between CloudFront and your custom origin. 7. Confirm the following before you use the updated configuration in a production environment: • The path pattern in each cache behavior applies only to the requests that you want viewers to use HTTPS for. • The cache behaviors are listed in the order that you want CloudFront to evaluate them in. For more information, see Path pattern. • The cache behaviors are routing requests to the origins that you changed the Origin Protocol Policy for. Install an SSL/TLS certificate on your custom origin You can use an SSL/TLS certificate from the following sources on your custom origin: • If your origin is an Elastic Load Balancing load balancer, you can use a certificate provided by AWS Certificate Manager (ACM). You also can use a certificate that is signed by a trusted third- party certificate authority and imported into ACM. • For origins other than Elastic Load Balancing load balancers, you must use a certificate that is signed by a trusted third-party certificate authority (CA), for example, Comodo, DigiCert, or Symantec. The certificate returned from the origin must include one of the following domain names: • The domain name in the origin’s Origin domain field (the DomainName field in the CloudFront API). • The domain name in the Host header, if the cache behavior is configured to forward the Host header to the origin. When CloudFront uses HTTPS to communicate with your origin, CloudFront verifies that the certificate was issued by a trusted certificate authority. CloudFront supports the same certificate Require HTTPS to a custom origin 376 Amazon CloudFront Developer Guide authorities that Mozilla does. For the current list, see Mozilla Included CA Certificate List. You can’t use a self-signed certificate for HTTPS communication between CloudFront and your origin. Important If the origin server returns an expired certificate, an invalid certificate, or a self-signed certificate, or if the origin server returns the certificate chain in the wrong order, CloudFront drops the TCP connection, returns HTTP status code 502 (Bad Gateway) to the viewer, and sets the X-Cache header to Error from cloudfront. Also, if the full chain of certificates, including the intermediate certificate, is not present, CloudFront drops the TCP connection. Require HTTPS for communication between CloudFront and your Amazon S3 origin When your origin is an Amazon S3 bucket, your options for using HTTPS for communications with CloudFront depend on how you're using the bucket. If your Amazon S3 bucket is configured as a website endpoint, you can't configure CloudFront to use HTTPS to communicate with your origin because Amazon S3 doesn't support HTTPS connections in that configuration. When your origin is an Amazon S3 bucket that supports HTTPS communication, CloudFront forwards requests to S3 by using the protocol that viewers used to submit the requests. The default setting for the Protocol (custom origins only) setting is Match Viewer and can't be changed. However, if you enable origin access control (OAC) for your Amazon S3 origin, the communication used between CloudFront and Amazon S3 depends on your settings. For more information, see Create a new origin access control. If you want to require HTTPS for communication between CloudFront and Amazon S3, you must change the value of Viewer Protocol Policy to Redirect HTTP to HTTPS or HTTPS Only. The procedure later in this section explains how to use the CloudFront console to change Viewer Protocol Policy. For information about using the CloudFront API to update the ViewerProtocolPolicy element for a distribution, see UpdateDistribution in the Amazon CloudFront API Reference. When you use HTTPS with an Amazon S3 bucket that supports HTTPS communication, Amazon S3 provides the SSL/TLS certificate, so you don't have to. Require HTTPS to an Amazon S3 origin 377 Amazon CloudFront Developer Guide Require HTTPS for an Amazon S3 origin The following procedure shows you how to configure CloudFront to require HTTPS to your Amazon S3 origin. To configure CloudFront to require HTTPS to your Amazon S3 origin 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. |
AmazonCloudFront_DevGuide-148 | AmazonCloudFront_DevGuide.pdf | 148 | element for a distribution, see UpdateDistribution in the Amazon CloudFront API Reference. When you use HTTPS with an Amazon S3 bucket that supports HTTPS communication, Amazon S3 provides the SSL/TLS certificate, so you don't have to. Require HTTPS to an Amazon S3 origin 377 Amazon CloudFront Developer Guide Require HTTPS for an Amazon S3 origin The following procedure shows you how to configure CloudFront to require HTTPS to your Amazon S3 origin. To configure CloudFront to require HTTPS to your Amazon S3 origin 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the top pane of the CloudFront console, choose the ID for the distribution that you want to update. 3. On the Behaviors tab, choose the cache behavior that you want to update, and then choose Edit. 4. Specify one of the following values for Viewer Protocol Policy: Redirect HTTP to HTTPS Viewers can use both protocols, but HTTP requests are automatically redirected to HTTPS requests. CloudFront returns HTTP status code 301 (Moved Permanently) along with the new HTTPS URL. The viewer then resubmits the request to CloudFront using the HTTPS URL. Important CloudFront doesn't redirect DELETE, OPTIONS, PATCH, POST, or PUT requests from HTTP to HTTPS. If you configure a cache behavior to redirect to HTTPS, CloudFront responds to HTTP DELETE, OPTIONS, PATCH, POST, or PUT requests for that cache behavior with HTTP status code 403 (Forbidden). When a viewer makes an HTTP request that is redirected to an HTTPS request, CloudFront charges for both requests. For the HTTP request, the charge is only for the request and for the headers that CloudFront returns to the viewer. For the HTTPS request, the charge is for the request, and for the headers and the object returned by your origin. Require HTTPS to an Amazon S3 origin 378 Amazon CloudFront HTTPS Only Developer Guide Viewers can access your content only if they're using HTTPS. If a viewer sends an HTTP request instead of an HTTPS request, CloudFront returns HTTP status code 403 (Forbidden) and does not return the object. 5. Choose Yes, Edit. 6. Repeat steps 3 through 5 for each additional cache behavior that you want to require HTTPS for between viewers and CloudFront, and between CloudFront and S3. 7. Confirm the following before you use the updated configuration in a production environment: • The path pattern in each cache behavior applies only to the requests that you want viewers to use HTTPS for. • The cache behaviors are listed in the order that you want CloudFront to evaluate them in. For more information, see Path pattern. • The cache behaviors are routing requests to the correct origins. Supported protocols and ciphers between viewers and CloudFront When you require HTTPS between viewers and your CloudFront distribution, you must choose a security policy, which determines the following settings: • The minimum SSL/TLS protocol that CloudFront uses to communicate with viewers. • The ciphers that CloudFront can use to encrypt the communication with viewers. To choose a security policy, specify the applicable value for Security policy (minimum SSL/TLS version). The following table lists the protocols and ciphers that CloudFront can use for each security policy. A viewer must support at least one of the supported ciphers to establish an HTTPS connection with CloudFront. CloudFront chooses a cipher in the listed order from among the ciphers that the viewer supports. See also OpenSSL, s2n, and RFC cipher names. Supported protocols and ciphers between viewers and CloudFront 379 Amazon CloudFront Developer Guide Security policy SSLv3 TLSv1 Supported SSL/TLS protocols TLSv1_201 6 TLSv1.1_2 016 TLSv1.2_2 018 TLSv1.2_2 019 TLSv1.2_2 021 TLSv1.3 TLSv1.2 TLSv1.1 TLSv1 SSLv3 Supported TLSv1.3 ciphers TLS_AES_128_GCM_SH A256 TLS_AES_256_GCM_SH A384 TLS_CHACHA20_POLY1 305_SHA256 Supported ECDSA ciphers ECDHE-ECDSA-AES128- GCM-SHA256 ECDHE-ECDSA-AES128- SHA256 ECDHE-ECDSA-AES128- SHA ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Supported protocols and ciphers between viewers and CloudFront 380 Amazon CloudFront Developer Guide Security policy SSLv3 TLSv1 TLSv1_201 6 TLSv1.1_2 016 TLSv1.2_2 018 TLSv1.2_2 019 TLSv1.2_2 021 ECDHE-ECDSA-AES256- GCM-SHA384 ECDHE-ECDSA-CHACHA 20-POLY1305 ECDHE-ECDSA-AES256- SHA384 ECDHE-ECDSA-AES256- SHA Supported RSA ciphers ECDHE-RSA-AES128-GCM- SHA256 ECDHE-RSA-AES128-S HA256 ECDHE-RSA-AES128-SHA ECDHE-RSA-AES256-GCM- SHA384 ECDHE-RSA-CHACHA20- POLY1305 ECDHE-RSA-AES256-S HA384 ECDHE-RSA-AES256-SHA AES128-GCM-SHA256 ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ |
AmazonCloudFront_DevGuide-149 | AmazonCloudFront_DevGuide.pdf | 149 | Guide Security policy SSLv3 TLSv1 TLSv1_201 6 TLSv1.1_2 016 TLSv1.2_2 018 TLSv1.2_2 019 TLSv1.2_2 021 ECDHE-ECDSA-AES256- GCM-SHA384 ECDHE-ECDSA-CHACHA 20-POLY1305 ECDHE-ECDSA-AES256- SHA384 ECDHE-ECDSA-AES256- SHA Supported RSA ciphers ECDHE-RSA-AES128-GCM- SHA256 ECDHE-RSA-AES128-S HA256 ECDHE-RSA-AES128-SHA ECDHE-RSA-AES256-GCM- SHA384 ECDHE-RSA-CHACHA20- POLY1305 ECDHE-RSA-AES256-S HA384 ECDHE-RSA-AES256-SHA AES128-GCM-SHA256 ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Supported protocols and ciphers between viewers and CloudFront 381 Amazon CloudFront Developer Guide Security policy SSLv3 TLSv1 AES256-GCM-SHA384 AES128-SHA256 AES256-SHA AES128-SHA DES-CBC3-SHA RC4-MD5 ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ OpenSSL, s2n, and RFC cipher names TLSv1_201 6 TLSv1.1_2 016 TLSv1.2_2 018 TLSv1.2_2 019 TLSv1.2_2 021 ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ OpenSSL and s2n use different names for ciphers than the TLS standards use (RFC 2246, RFC 4346, RFC 5246, and RFC 8446). The following table maps the OpenSSL and s2n names to the RFC name for each cipher. For ciphers with elliptic curve key exchange algorithms, CloudFront supports the following elliptic curves: • prime256v1 • X25519 • secp384r1 For more information about certificate requirements for CloudFront, see Requirements for using SSL/TLS certificates with CloudFront. OpenSSL and s2n cipher name RFC cipher name Supported TLSv1.3 ciphers TLS_AES_128_GCM_SHA256 TLS_AES_128_GCM_SHA256 Supported protocols and ciphers between viewers and CloudFront 382 Amazon CloudFront Developer Guide OpenSSL and s2n cipher name RFC cipher name TLS_AES_256_GCM_SHA384 TLS_AES_256_GCM_SHA384 TLS_CHACHA20_POLY1305_SHA256 TLS_CHACHA20_POLY1305_SHA256 Supported ECDSA ciphers ECDHE-ECDSA-AES128-GCM-SHA256 TLS_ECDHE_ECDSA_WITH_AES_12 8_GCM_SHA256 ECDHE-ECDSA-AES128-SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 256 ECDHE-ECDSA-AES128-SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305 TLS_ECDHE_ECDSA_WITH_AES_25 6_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_CHACHA 20_POLY1305_SHA256 ECDHE-ECDSA-AES256-SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 384 ECDHE-ECDSA-AES256-SHA TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA Supported RSA ciphers ECDHE-RSA-AES128-GCM-SHA256 TLS_ECDHE_RSA_WITH_AES_128_ GCM_SHA256 ECDHE-RSA-AES128-SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA25 6 ECDHE-RSA-AES128-SHA TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA ECDHE-RSA-AES256-GCM-SHA384 TLS_ECDHE_RSA_WITH_AES_256_ GCM_SHA384 Supported protocols and ciphers between viewers and CloudFront 383 Amazon CloudFront Developer Guide OpenSSL and s2n cipher name RFC cipher name ECDHE-RSA-CHACHA20-POLY1305 TLS_ECDHE_RSA_WITH_CHACHA20 _POLY1305_SHA256 ECDHE-RSA-AES256-SHA384 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA38 4 ECDHE-RSA-AES256-SHA TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA AES128-GCM-SHA256 TLS_RSA_WITH_AES_128_GCM_SHA256 AES256-GCM-SHA384 TLS_RSA_WITH_AES_256_GCM_SHA384 AES128-SHA256 TLS_RSA_WITH_AES_128_CBC_SHA256 AES256-SHA AES128-SHA DES-CBC3-SHA RC4-MD5 TLS_RSA_WITH_AES_256_CBC_SHA TLS_RSA_WITH_AES_128_CBC_SHA TLS_RSA_WITH_3DES_EDE_CBC_SHA TLS_RSA_WITH_RC4_128_MD5 Supported signature schemes between viewers and CloudFront CloudFront supports the following signature schemes for connections between viewers and CloudFront. Security policy Signature schemes SSLv3 TLSv1 TLSv1_201 6 TLSv1.1_2 016 TLSv1.2_2 018 TLSv1.2_2 019 and TLSv1.2_2 ♦ ♦ ♦ ♦ ♦ ♦ ♦ 021 TLS_SIGNATURE_SCHE ME_RSA_PSS_PSS_SHA 256 Supported protocols and ciphers between viewers and CloudFront 384 Amazon CloudFront Developer Guide Security policy Signature schemes SSLv3 TLSv1 TLSv1_201 6 TLSv1.1_2 016 TLSv1.2_2 018 TLSv1.2_2 019 and TLSv1.2_2 TLS_SIGNATURE_SCHE ME_RSA_PSS_PSS_SHA 384 TLS_SIGNATURE_SCHE ME_RSA_PSS_PSS_SHA 512 TLS_SIGNATURE_SCHE ME_RSA_PSS_RSAE_SH A256 TLS_SIGNATURE_SCHE ME_RSA_PSS_RSAE_SH A384 TLS_SIGNATURE_SCHE ME_RSA_PSS_RSAE_SH A512 TLS_SIGNATURE_SCHE ME_RSA_PKCS1_SHA256 TLS_SIGNATURE_SCHE ME_RSA_PKCS1_SHA384 TLS_SIGNATURE_SCHE ME_RSA_PKCS1_SHA512 TLS_SIGNATURE_SCHE ME_RSA_PKCS1_SHA224 ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ 021 ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Supported protocols and ciphers between viewers and CloudFront 385 Amazon CloudFront Developer Guide Security policy Signature schemes SSLv3 TLSv1 TLSv1_201 6 TLSv1.1_2 016 TLSv1.2_2 018 TLSv1.2_2 019 and TLSv1.2_2 ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ 021 ♦ ♦ ♦ ♦ ♦ ♦ TLS_SIGNATURE_SCHE ME_ECDSA_SHA256 TLS_SIGNATURE_SCHE ME_ECDSA_SHA384 TLS_SIGNATURE_SCHE ME_ECDSA_SHA512 TLS_SIGNATURE_SCHE ME_ECDSA_SHA224 TLS_SIGNATURE_SCHE ME_ECDSA_SECP256R1 _SHA256 TLS_SIGNATURE_SCHE ME_ECDSA_SECP384R1 _SHA384 TLS_SIGNATURE_SCHE ME_RSA_PKCS1_SHA1 TLS_SIGNATURE_SCHE ME_ECDSA_SHA1 ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Supported protocols and ciphers between CloudFront and the origin If you choose to require HTTPS between CloudFront and your origin, you can decide which SSL/TLS protocol to allow for the secure connection, and CloudFront can connect to the origin using any of the ECDSA or RSA ciphers listed in the following table. Your origin must support at least one of these ciphers for CloudFront to establish an HTTPS connection to your origin. Supported protocols and ciphers between CloudFront and the origin 386 Amazon CloudFront Developer Guide OpenSSL and s2n use different names for ciphers than the TLS standards use (RFC 2246, RFC 4346, RFC 5246, and RFC 8446). The following table includes the OpenSSL and s2n name, and the RFC name, for each cipher. For ciphers with elliptic curve key exchange algorithms, CloudFront supports the following elliptic curves: • prime256v1 • secp384r1 • X25519 OpenSSL and s2n cipher name RFC cipher name Supported ECDSA ciphers ECDHE-ECDSA-AES256-GCM-SHA384 TLS_ECDHE_ECDSA_WITH_AES_25 6_GCM_SHA384 ECDHE-ECDSA-AES256-SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 384 ECDHE-ECDSA-AES256-SHA TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ECDHE-ECDSA-AES128-GCM-SHA256 TLS_ECDHE_ECDSA_WITH_AES_12 8_GCM_SHA256 ECDHE-ECDSA-AES128-SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 256 ECDHE-ECDSA-AES128-SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA Supported RSA ciphers ECDHE-RSA-AES256-GCM-SHA384 TLS_ECDHE_RSA_WITH_AES_256_ GCM_SHA384 ECDHE-RSA-AES256-SHA384 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA38 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.