

# 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 [Use Amazon CloudFront Origin Shield](origin-shield.md).

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](cache-statistics.md).

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)](cache-hit-ratio.md).

To learn about adding and removing the content that you want CloudFront to serve, see [Add, remove, or replace content that CloudFront distributes](AddRemoveReplaceObjects.md).

**Topics**
+ [

# Increase the proportion of requests that are served directly from the CloudFront caches (cache hit ratio)
](cache-hit-ratio.md)
+ [

# Use Amazon CloudFront Origin Shield
](origin-shield.md)
+ [

# Optimize high availability with CloudFront origin failover
](high_availability_origin_failover.md)
+ [

# Manage how long content stays in the cache (expiration)
](Expiration.md)
+ [

# Cache content based on query string parameters
](QueryStringParameters.md)
+ [

# Cache content based on cookies
](Cookies.md)
+ [

# Cache content based on request headers
](header-caching.md)

# Increase the proportion of requests that are served directly from the CloudFront caches (cache hit ratio)
Improve your 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
](#cache-hit-ratio-duration)
+ [

## Use Origin Shield
](#cache-hit-ratio-use-origin-shield)
+ [

## Caching based on query string parameters
](#cache-hit-ratio-query-string-parameters)
+ [

## Caching based on cookie values
](#cache-hit-ratio-cookies)
+ [

## Caching based on request headers
](#cache-hit-ratio-request-headers)
+ [

## Remove `Accept-Encoding` header when compression is not needed
](#cache-hit-ratio-remove-accept-encoding)
+ [

## Serve media content over HTTP
](#cache-hit-ratio-http-streaming)

## 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](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) 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)](Expiration.md).

## 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 all other layers of the CloudFront cache (edge locations and [regional edge caches](HowCloudFrontWorks.md#CloudFrontRegionaledgecaches)) can retrieve the object from Origin Shield.

For more information, see [Use Amazon CloudFront Origin Shield](origin-shield.md).

## 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&parameter2=b` and another request for the same object contains `parameter2=b&parameter1=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](QueryStringParameters.md). 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 [Access logs (standard logs)](AccessLogs.md).

## 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.

  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](Cookies.md). 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 [Access logs (standard logs)](AccessLogs.md).

## 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.
**Note**  
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](RequestAndResponseBehaviorS3Origin.md#request-s3-removed-headers)
How CloudFront processes and forwards requests to your custom origin server > [HTTP request headers and CloudFront behavior (custom and Amazon S3 origins)](RequestAndResponseBehaviorCustomOrigin.md#request-custom-headers-behavior)

  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](header-caching.md).

## 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)

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](on-demand-streaming-video.md).

# Use Amazon CloudFront Origin Shield
Use 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](HowCloudFrontWorks.md#CloudFrontRegionaledgecaches)) can retrieve the object from Origin Shield.

**Reduced origin load**  
Origin Shield can further reduce the number of [simultaneous requests](RequestAndResponseBehaviorCustomOrigin.md#request-custom-traffic-spikes) 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](#choose-origin-shield-region), 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.

You incur additional charges for using Origin Shield. For more information, see [CloudFront pricing](https://aws.amazon.com/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](distribution-using-grpc.md).

**Topics**
+ [

## Use cases for Origin Shield
](#origin-shield-use-cases)
+ [

## Choose the AWS Region for Origin Shield
](#choose-origin-shield-region)
+ [

## Enable Origin Shield
](#enable-origin-shield)
+ [

## Estimate Origin Shield costs
](#origin-shield-costs)
+ [

## Origin Shield high availability
](#origin-shield-high-availability)
+ [

## How Origin Shield interacts with other CloudFront features
](#origin-shield-and-other-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.

**Topics**
+ [

### Viewers in different geographical regions
](#os-use-cases-global-viewers)
+ [

### Multiple CDNs
](#os-use-cases-multi-cdn)

### 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](https://aws.amazon.com/cloudfront/features/#Amazon_CloudFront_Infrastructure), [regional edge caches](HowCloudFrontWorks.md#CloudFrontRegionaledgecaches) 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.

![\[Without CloudFront Origin Shield, the origin might receive duplicate requests.\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/images/origin-shield-without.png)


**With Origin Shield**

Using Origin Shield can help reduce the load on your origin, as shown in the following diagram.

![\[With CloudFront Origin Shield, the origin can receive fewer duplicate requests.\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/images/origin-shield-with.png)


### 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](controlling-the-cache-key.md) 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 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](https://aws.amazon.com/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.

![\[Graphic that shows how an origin can receive duplicate requests, each coming from a different CDN.\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/images/origin-shield-without-multi-cdn.png)


**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.

![\[Graphic that shows CloudFront Origin Shield receiving fewer duplicate requests.\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/images/origin-shield-with-multi-cdn.png)


## Choose the AWS Region for Origin Shield


Amazon CloudFront offers Origin Shield in AWS Regions where CloudFront has a [regional edge cache](HowCloudFrontWorks.md#CloudFrontRegionaledgecaches). 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`
+ 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.
+ 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.

## Enable 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 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](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose the distribution that has the origin that you want to update.

1. Choose the **Origins** tab.

1. Choose the origin to update, then choose **Edit**.

1. For **Enable Origin Shield**, choose **Yes**.

1. For **Origin Shield Region**, choose the AWS Region where you want to enable Origin Shield. For help choosing a Region, see [Choose the AWS Region for Origin Shield](#choose-origin-shield-region).

1. Choose **Save changes**.

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](https://console.aws.amazon.com/cloudfront/v4/home).

1. To create the new origin in an existing distribution, do the following:

   1. Choose the distribution where you want to create the origin.

   1. Choose **Create Origin**, and then proceed to step 3.

   To create the new origin in a new standard distribution, do the following:

   1. Follow the steps to create a standard distribution in the console. For more information, see [Create a CloudFront distribution in the console](distribution-web-creating-console.md#create-console-distribution).

   1. In the **Settings** section, choose **Customize origin settings**. Proceed to step 3.

1. For **Enable Origin Shield**, choose **Yes**.

1. For **Origin Shield Region**, choose the AWS Region where you want to enable Origin Shield. For help choosing a Region, see [Choose the AWS Region for Origin Shield](#choose-origin-shield-region).

1. Follow the steps in the console to finish creating your origin or distribution.

When your distribution status is **Deployed**, Origin Shield is ready. This takes a few minutes.

------
#### [ CloudFormation ]

To enable Origin Shield with 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 [Choose the AWS Region for Origin Shield](#choose-origin-shield-region). 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
  CustomOriginConfig:
    OriginProtocolPolicy: match-viewer
    OriginSSLProtocols: TLSv1
```

For more information, see [AWS::CloudFront::Distribution Origin](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-origin.html) 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](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_OriginShield.html) (type)
+ [Origin](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_Origin.html) (type)
+ [DistributionConfig](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_DistributionConfig.html) (type)
+ [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html) (operation)
+ [CreateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html) (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.

------

## Estimate 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

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](HowCloudFrontWorks.md#CloudFrontRegionaledgecaches) 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](https://aws.amazon.com/cloudfront/pricing/).

## Origin Shield high availability


Origin Shield leverages the CloudFront [regional edge caches](HowCloudFrontWorks.md#CloudFrontRegionaledgecaches) feature. Each of these edge caches is built in an AWS Region using at least three [Availability Zones](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/) 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)](AccessLogs.md). Standard logs are provided free of charge.
+ [CloudFront real-time access logs](real-time-logs.md). You incur additional charges for using real-time access logs. See [Amazon CloudFront Pricing](https://aws.amazon.com/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](HowCloudFrontWorks.md#CloudFrontRegionaledgecaches). 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](high_availability_origin_failover.md). 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](lambda-at-the-edge.md) functions, but it can affect the AWS Region where those functions run.

When you use Origin Shield with Lambda@Edge, [origin-facing triggers](lambda-cloudfront-trigger-events.md) (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
Increase availability with 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](#concept_origin_groups.creating).

After you configure origin failover for a cache behavior, CloudFront does the following for viewer requests:
+ 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 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](#controlling-attempts-and-timeouts).

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).

**Note**  
CloudFront will not failover if `OPTIONS` are not set as a [Cached HTTP methods](DownloadDistValuesCacheBehavior.md#DownloadDistValuesCachedHTTPMethods) in your cache behavior.

The following diagram illustrates how origin failover works.

![\[How origin failover works\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/images/origingroups-overview.png)


**Topics**
+ [

## Create an origin group
](#concept_origin_groups.creating)
+ [

## Control origin timeouts and attempts
](#controlling-attempts-and-timeouts)
+ [

## Use origin failover with Lambda@Edge functions
](#concept_origin_groups.lambda)
+ [

## Use custom error pages with origin failover
](#concept_origin_groups.custom-error)

## Create an origin group
<a name="create-origin-groups-procedure"></a>

**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](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose the distribution that you want to create the origin group for.

1. Choose the **Origins** tab.

1. Make sure the distribution has more than one origin. If it doesn’t, add a second origin.

1. On the **Origins** tab, in the **Origin groups** pane, choose **Create origin group**.

1. 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.

1. Enter a name for the origin group.

1. Choose the HTTP status codes to use as failover criteria. You can choose any combination of the following status codes: 400, 403, 404, 416, 429, 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).

1. 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](media-quality-score.md). 

1. 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](DownloadDistValuesOrigin.md#DownloadDistValuesId).

## 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 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](DownloadDistValuesOrigin.md#origin-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](DownloadDistValuesOrigin.md#origin-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**  
The origin response timeout, also known as the origin read timeout,  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–120 seconds (inclusive). For more information, see [Response timeout](DownloadDistValuesOrigin.md#DownloadDistValuesOriginResponseTimeout).

### How to change these settings


**To change these settings in the [CloudFront console](https://console.aws.amazon.com/cloudfront/v4/home)**
+ For a new origin or a new distribution, you specify these values when you create the resource.
+ For an existing origin in an existing distribution, you specify these values when you edit the origin.

For more information, see [All distribution settings reference](distribution-web-values-specify.md).

## 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](lambda-cloudfront-trigger-events.md) 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.

1. The Lambda function is triggered once when CloudFront sends a request to the primary origin (on a cache miss).

1. The primary origin responds with an HTTP status code that’s configured for failover.

1. 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.

![\[How origin failover works with Lambda@Edge functions\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/images/origingroups-with-lambda-edge.png)


For more information about using Lambda@Edge triggers, see [Add triggers for a Lambda@Edge function](lambda-edge-add-triggers.md).

For more information about managing DNS failover, see [Configuring DNS failover](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring.html) 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.

For more information about using custom error pages with CloudFront, see [Generate custom error responses](GeneratingCustomErrorResponses.md).

# Manage how long content stays in the cache (expiration)
Manage 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 `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](DownloadDistValuesCacheBehavior.md#DownloadDistValuesMinTTL), [Maximum TTL](DownloadDistValuesCacheBehavior.md#DownloadDistValuesMaxTTL), and [Default TTL](DownloadDistValuesCacheBehavior.md#DownloadDistValuesDefaultTTL).
+ 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](#expiration-individual-objects).

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 [Specify the amount of time that CloudFront caches objects](#ExpirationDownloadDist).

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 [How CloudFront processes HTTP 4xx and 5xx status codes from your origin](HTTPStatusCodes.md).

**Topics**
+ [

## Use headers to control cache duration for individual objects
](#expiration-individual-objects)
+ [

## Serve stale (expired) content
](#stale-content)
+ [

## Specify the amount of time that CloudFront caches objects
](#ExpirationDownloadDist)
+ [

## Add headers to your objects by using the Amazon S3 console
](#ExpirationAddingHeadersInS3)

## 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](#ExpirationDownloadDist).
+ 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](https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1), 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](#ExpirationDownloadDist).

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](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9)
+ [Section 14.21 Expires](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21)

## Serve stale (expired) content
Support for serving stale (expired) cache content

CloudFront supports the `Stale-While-Revalidate` and `Stale-If-Error` cache control directives.

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-while-revalidate)
+ [

### `Stale-If-Error`
](#stale-if-error-only)
+ [

### Use both directives
](#use-both-stale-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.

**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`).

1. 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. 

1. 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](DownloadDistValuesCacheBehavior.md#DownloadDistValuesMaxTTL), 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: `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`).

1. 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`)

1. 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 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](GeneratingCustomErrorResponses.md).

**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](DownloadDistValuesCacheBehavior.md#DownloadDistValuesMaxTTL), 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](HTTPStatusCodes.md#HTTPStatusCodes-no-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: 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`). 

1. 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. 

1. 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`).

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:
+ Set the minimum, maximum, and default TTL values in a CloudFront distribution's cache behavior. You can set these values in a [cache policy](controlling-the-cache-key.md) 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 caches the object for the lesser of the value of the `Cache-Control: max-age` directive or the value of the CloudFront maximum TTL. **Browser caching** Browsers cache the object for the value of the `Cache-Control: max-age` directive.  |  **CloudFront caching** CloudFront caching depends on the values of the CloudFront minimum TTL and maximum TTL and the `Cache-Control max-age` directive: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) **Browser caching** Browsers cache the object for the value of the `Cache-Control: max-age` directive.  | 
|  **The origin does not add a `Cache-Control: max-age` directive to the object**  |  **CloudFront caching** CloudFront caches the object for the value of the CloudFront default TTL. **Browser caching** Depends on the browser.  |  **CloudFront caching** CloudFront caches the object for the greater of the value of the CloudFront minimum TTL or default TTL. **Browser caching** Depends on the browser.  | 
|  **The origin adds `Cache-Control: max-age` and `Cache-Control: s-maxage` directives to the object**  |  **CloudFront caching** CloudFront caches the object for the lesser of the value of 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-Control max-age` directive.  |  **CloudFront caching** CloudFront caching depends on the values of the CloudFront minimum TTL and maximum TTL and the `Cache-Control: s-maxage` directive: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) **Browser caching** Browsers cache the object for the value of the `Cache-Control: max-age` directive.  | 
|  **The origin adds an `Expires` header to the object**  |  **CloudFront caching** CloudFront caches the object until the date in the `Expires` header or for the value of the CloudFront maximum TTL, whichever is sooner. **Browser caching** Browsers cache the object until the date in the `Expires` header.  |  **CloudFront caching** CloudFront caching depends on the values of the CloudFront minimum TTL and maximum TTL and the `Expires` header: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) **Browser caching** Browsers cache the object until the date and time in the `Expires` header.  | 
|  **Origin adds `Cache-Control: no-cache`, `no-store`, and/or `private` directives to the object**  |  CloudFront and browsers respect the headers.  |  **CloudFront caching** CloudFront caches the object for the value of the CloudFront minimum TTL. [See the warning below this table](#stale-if-error). **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.
CloudFront doesn't cache the HTTP 501 status code (Not Implemented) from an S3 origin when the origin headers include the `Cache-Control: no-cache`, `no-store`, and/or `private` directives. This is the default behavior for an S3 origin, even if your [minimum TTL](DownloadDistValuesCacheBehavior.md#DownloadDistValuesMinTTL) setting is greater than 0.

For information about how to change settings for distributions using the CloudFront console, see [Update a distribution](HowToUpdateDistribution.md). For information about how to change settings for distributions using the CloudFront API, see [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html).

## 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.

**To add a `Cache-Control` or `Expires` header field to Amazon S3 objects**

1. Follow the procedure in the **Replacing system-defined metadata** section on the [Editing object metadata in the Amazon S3 console](https://docs.aws.amazon.com/AmazonS3/latest/userguide/add-object-metadata.html) topic in the *Amazon S3 User Guide*.

1. For **Key**, choose the name of the header that you are adding (**Cache-Control** or **Expires**).

1. 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`.

1. Follow the rest of the procedure to save your metadata changes.

# Cache content based on query string parameters
Caching and 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`
+ `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.
+ 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 [Optimize caching](#query-string-parameters-optimizing-caching).

**Topics**
+ [

## Console and API settings for query string forwarding and caching
](#query-string-parameters-console)
+ [

## Optimize caching
](#query-string-parameters-optimizing-caching)
+ [

## Query string parameters and CloudFront standard logs (access logs)
](#query-string-parameters-access-logs)

## Console and API settings for query string forwarding and caching


When you create a distribution in the CloudFront console, CloudFront configures query string forwarding and caching for you based on your origin type. Optionally, you can manually edit these settings. For more information, see the following settings in the [All distribution settings reference](distribution-web-values-specify.md):
+ [Query string forwarding and caching](DownloadDistValuesCacheBehavior.md#DownloadDistValuesQueryString)
+ [Query string allowlist](DownloadDistValuesCacheBehavior.md#DownloadDistValuesQueryStringAllowlist)

To configure query string forwarding and caching with the CloudFront API, see [CachePolicy](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CachePolicy.html) and [OriginRequestPolicy](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_OriginRequestPolicy.html) 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.  
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 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.

**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 [Access logs (standard logs)](AccessLogs.md).

# 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 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](DownloadDistValuesCacheBehavior.md), particularly the [Forward cookies](DownloadDistValuesCacheBehavior.md#DownloadDistValuesForwardCookies) and [Allowlist cookies](DownloadDistValuesCacheBehavior.md#DownloadDistValuesAllowlistCookies) 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 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](DownloadDistValuesCacheBehavior.md#DownloadDistValuesAllowlistCookies).

  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)](cloudfront-limits.md#limits-allowlisted-query-strings).
+ **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 [Access logs (standard logs)](AccessLogs.md).

**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.  
 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).

**Standard name–value pair format is required**  
CloudFront forwards a cookie header only if the value conforms to the [standard name–value pair format](https://tools.ietf.org/html/rfc6265#section-4.1.1), 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](https://tools.ietf.org/html/rfc7234#section-5.2.2) 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](HowToUpdateDistribution.md). For information about using the CloudFront API to update a distribution, see [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html) 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.

**Topics**
+ [

## Headers and distributions – overview
](#header-caching-web)
+ [

## Select the headers to base caching on
](#header-caching-web-selecting)
+ [

## Configure CloudFront to respect CORS settings
](#header-caching-web-cors)
+ [

## Configure caching based on the device type
](#header-caching-web-device)
+ [

## Configure caching based on the language of the viewer
](#header-caching-web-language)
+ [

## Configure caching based on the location of the viewer
](#header-caching-web-location)
+ [

## Configure caching based on the protocol of the request
](#header-caching-web-protocol)
+ [

## Configure caching for compressed files
](#header-caching-web-compressed)
+ [

## How caching based on headers affects performance
](#header-caching-web-performance)
+ [

## How the case of headers and header values affects caching
](#header-caching-web-case)
+ [

## Headers that CloudFront returns to the viewer
](#header-caching-web-response)

## 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesForwardHeaders).

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
**Note**  
**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](cloudfront-limits.md#limits-custom-headers).

For information about using the CloudFront console to update a distribution so CloudFront forwards headers to the origin, see [Update a distribution](HowToUpdateDistribution.md). For information about using the CloudFront API to update an existing distribution, see [Update Distribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html) 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](#header-caching-web-cors). 
  + 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 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](lambda-examples.md#lambda-examples-redirecting-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](Cookies.md).
  + `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)](RequestAndResponseBehaviorCustomOrigin.md#request-custom-headers-behavior).

## 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 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](controlling-the-cache-key.md).

For more information about CORS and Amazon S3, see [Using cross-origin resource sharing (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html) 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 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](https://en.wikipedia.org/wiki/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:
+ 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](RequestAndResponseBehaviorS3Origin.md#response-s3-removed-headers).
+ **Custom origins – ** See [HTTP response headers that CloudFront removes or replaces](RequestAndResponseBehaviorCustomOrigin.md#ResponseCustomRemovedHeaders).