

# Request and response behavior
<a name="RequestAndResponseBehavior"></a>

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](HTTPandHTTPSRequests.md)
+ [Request and response behavior for Amazon S3 origins](RequestAndResponseBehaviorS3Origin.md)
+ [Request and response behavior for custom origins](RequestAndResponseBehaviorCustomOrigin.md)
+ [Request and response behavior for origin groups](RequestAndResponseBehaviorOriginGroups.md)
+ [Add custom headers to origin requests](add-origin-custom-headers.md)
+ [How CloudFront processes partial requests for an object (range GETs)](RangeGETs.md)
+ [How CloudFront processes HTTP 3xx status codes from your origin](http-3xx-status-codes.md)
+ [How CloudFront processes HTTP 4xx and 5xx status codes from your origin](HTTPStatusCodes.md)
+ [Generate custom error responses](GeneratingCustomErrorResponses.md)

# How CloudFront processes HTTP and HTTPS requests
<a name="HTTPandHTTPSRequests"></a>

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](RequestAndResponseBehaviorCustomOrigin.md#RequestCustomProtocols).

For information about how to restrict your distribution so that end users can only access objects using HTTPS, see [Use HTTPS with CloudFront](using-https.md).

**Note**  
The charge for HTTPS requests is higher than the charge for HTTP requests. For more information about billing rates, see [CloudFront pricing](https://aws.amazon.com/cloudfront/#pricing).

# Request and response behavior for Amazon S3 origins
<a name="RequestAndResponseBehaviorS3Origin"></a>

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](#RequestBehaviorS3Origin)
+ [How CloudFront processes responses from your Amazon S3 origin](#ResponseBehaviorS3Origin)

## How CloudFront processes and forwards requests to your Amazon S3 origin
<a name="RequestBehaviorS3Origin"></a>

Learn about how CloudFront processes viewer requests and forwards the requests to your Amazon S3 origin.

**Contents**
+ [Caching duration and minimum TTL](#RequestS3Caching)
+ [Client IP addresses](#RequestS3IPAddresses)
+ [Conditional GET requests](#RequestS3ConditionalGETs)
+ [Cookies](#RequestS3Cookies)
+ [Cross-origin resource sharing (CORS)](#RequestS3-cors)
+ [GET requests that include a body](#RequestS3-get-body)
+ [HTTP methods](#RequestS3HTTPMethods)
+ [HTTP request headers that CloudFront removes or updates](#request-s3-removed-headers)
+ [Maximum length of a request and maximum length of a URL](#RequestS3MaxRequestStringLength)
+ [OCSP stapling](#request-s3-ocsp-stapling)
+ [Protocols](#RequestS3Protocol)
+ [Query strings](#RequestS3QueryStrings)
+ [Origin connection timeout and attempts](#s3-origin-timeout-attempts)
+ [Origin response timeout](#RequestS3RequestTimeout)
+ [Simultaneous requests for the same object (request collapsing)](#request-s3-traffic-spikes)

### Caching duration and minimum TTL
<a name="RequestS3Caching"></a>

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

### Client IP addresses
<a name="RequestS3IPAddresses"></a>

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
<a name="RequestS3ConditionalGETs"></a>

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 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
<a name="RequestS3Cookies"></a>

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)
<a name="RequestS3-cors"></a>

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

### GET requests that include a body
<a name="RequestS3-get-body"></a>

If a viewer `GET` request includes a body, CloudFront returns an HTTP status code 403 (Forbidden) to the viewer.

### HTTP methods
<a name="RequestS3HTTPMethods"></a>

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`
+ `GET`
+ `HEAD`
+ `OPTIONS`
+ `PATCH`
+ `POST`
+ `PUT`

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 [Restrict access to an Amazon S3 origin](private-content-restricting-access-to-s3.md).

**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 [Restrict access to an Amazon S3 origin](private-content-restricting-access-to-s3.md).

For information about the operations supported by Amazon S3, see the [ Amazon S3 documentation](https://docs.aws.amazon.com/s3/index.html).

### HTTP request headers that CloudFront removes or updates
<a name="request-s3-removed-headers"></a>

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)](RequestAndResponseBehaviorCustomOrigin.md#request-custom-headers-behavior).

### Maximum length of a request and maximum length of a URL
<a name="RequestS3MaxRequestStringLength"></a>

The maximum length of a request, including the path, the query string (if any), and headers, is 32,768 bytes.

CloudFront constructs a URL from the request. The maximum length of this URL is 8192 bytes.

If a URL exceeds the maximum length, CloudFront returns HTTP status code 414 (URI Too Long) to the viewer. If a request exceeds the maximum length because the header size is exceeded, CloudFront returns HTTP status code 494 to the viewer. In both cases, CloudFront then terminates the TCP connection to the viewer.

### OCSP stapling
<a name="request-s3-ocsp-stapling"></a>

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
<a name="RequestS3Protocol"></a>

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.

### Query strings
<a name="RequestS3QueryStrings"></a>

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

### Origin connection timeout and attempts
<a name="s3-origin-timeout-attempts"></a>

*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](high_availability_origin_failover.md#controlling-attempts-and-timeouts).

### Origin response timeout
<a name="RequestS3RequestTimeout"></a>

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](DownloadDistValuesOrigin.md#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 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)
<a name="request-s3-traffic-spikes"></a>

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 [CloudFront and edge function logging](logging.md).

CloudFront only collapses requests that share a [*cache key*](understanding-the-cache-key.md). 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](using-managed-cache-policies.md).

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](controlling-the-cache-key.md), the [origin request policy](controlling-origin-requests.md), or the legacy cache settings.

## How CloudFront processes responses from your Amazon S3 origin
<a name="ResponseBehaviorS3Origin"></a>

Learn about how CloudFront processes responses from your Amazon S3 origin.

**Contents**
+ [Canceled requests](#response-s3-canceled-requests)
+ [HTTP response headers that CloudFront removes or updates](#response-s3-removed-headers)
+ [Maximum cacheable file size](#ResponseS3MaxFileSize)
+ [Redirects](#ResponseS3Redirects)

### Canceled requests
<a name="response-s3-canceled-requests"></a>

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
<a name="response-s3-removed-headers"></a>

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](Cookies.md).
+ `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`
+ `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
<a name="ResponseS3MaxFileSize"></a>

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](RangeGETs.md#cache-large-objects-with-range-requests).

### Redirects
<a name="ResponseS3Redirects"></a>

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

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.

1. CloudFront forwards the request to the Amazon S3 bucket that is the origin for your distribution.

1. Amazon S3 returns an HTTP status code 301 (Moved Permanently) as well as the new location.

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

1. 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
<a name="RequestAndResponseBehaviorCustomOrigin"></a>

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](#RequestBehaviorCustomOrigin)
+ [How CloudFront processes responses from your custom origin](#ResponseBehaviorCustomOrigin)

## How CloudFront processes and forwards requests to your custom origin
<a name="RequestBehaviorCustomOrigin"></a>

Learn about how CloudFront processes viewer requests and forwards the requests to your custom origin.

**Contents**
+ [Authentication](#RequestCustomClientAuth)
+ [Caching duration and minimum TTL](#RequestCustomCaching)
+ [Client IP addresses](#RequestCustomIPAddresses)
+ [Client-side SSL authentication](#RequestCustomClientSideSslAuth)
+ [Compression](#RequestCustomCompression)
+ [Conditional requests](#RequestCustomConditionalGETs)
+ [Cookies](#RequestCustomCookies)
+ [Cross-origin resource sharing (CORS)](#request-custom-cors)
+ [Encryption](#RequestCustomEncryption)
+ [GET requests that include a body](#RequestCustom-get-body)
+ [HTTP methods](#RequestCustomHTTPMethods)
+ [HTTP request headers and CloudFront behavior (custom and Amazon S3 origins)](#request-custom-headers-behavior)
+ [HTTP version](#RequestCustomHTTPVersion)
+ [Maximum length of a request and maximum length of a URL](#RequestCustomMaxRequestStringLength)
+ [OCSP stapling](#request-custom-ocsp-stapling)
+ [Persistent connections](#request-custom-persistent-connections)
+ [Protocols](#RequestCustomProtocols)
+ [Query strings](#RequestCustomQueryStrings)
+ [Origin connection timeout and attempts](#custom-origin-timeout-attempts)
+ [Origin response timeout](#request-custom-request-timeout)
+ [Simultaneous requests for the same object (request collapsing)](#request-custom-traffic-spikes)
+ [`User-Agent` header](#request-custom-user-agent-header)

### Authentication
<a name="RequestCustomClientAuth"></a>

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`

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](add-origin-custom-headers.md#add-origin-custom-headers-forward-authorization).

You can use HTTP or HTTPS to forward requests to your origin server. For more information, see [Use HTTPS with CloudFront](using-https.md).

### Caching duration and minimum TTL
<a name="RequestCustomCaching"></a>

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

### Client IP addresses
<a name="RequestCustomIPAddresses"></a>

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:

`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](https://datatracker.ietf.org/doc/html/rfc7239). You can also modify the header using CloudFront edge compute functions.

### Client-side SSL authentication
<a name="RequestCustomClientSideSslAuth"></a>

CloudFront supports mutual TLS (mTLS) authentication where both the client and server authenticate each other using certificates. With mTLS configured, CloudFront can validate client certificates during the TLS handshake and optionally run CloudFront Functions to implement custom validation logic.

For origins that request client-side certificates when mTLS is not configured, CloudFront drops the request.

For more information about configuring mTLS, see [Associate a CloudFront Connection Function](connection-functions.md).

CloudFront does not support client authentication with client-side SSL certificates. If an origin requests a client-side certificate, CloudFront drops the request. 

### Compression
<a name="RequestCustomCompression"></a>

For more information, see [Serve compressed files](ServingCompressedFiles.md). 

### Conditional requests
<a name="RequestCustomConditionalGETs"></a>

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

### Cookies
<a name="RequestCustomCookies"></a>

You can configure CloudFront to forward cookies to your origin. For more information, see [Cache content based on cookies](Cookies.md).

### Cross-origin resource sharing (CORS)
<a name="request-custom-cors"></a>

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

### Encryption
<a name="RequestCustomEncryption"></a>

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](DownloadDistValuesCacheBehavior.md#DownloadDistValuesViewerProtocolPolicy)
+ [Protocol (custom origins only)](DownloadDistValuesOrigin.md#DownloadDistValuesOriginProtocolPolicy)

CloudFront forwards HTTPS requests to the origin server using the SSLv3, TLSv1.0, TLSv1.1, TLSv1.2, and TLSv1.3 protocols. For custom origins, you can choose the SSL protocols that you want CloudFront to use when communicating with your origin:
+ If you're using the CloudFront console, choose protocols by using the **Origin SSL Protocols** check boxes. For more information, see [Create a distribution](distribution-web-creating-console.md). 
+ If you're using the CloudFront API, specify protocols by using the `OriginSslProtocols` element. For more information, see [ OriginSslProtocols](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_OriginSslProtocols.html) and [ DistributionConfig](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_DistributionConfig.html) in the *Amazon CloudFront API Reference*.

If the origin is an Amazon S3 bucket, CloudFront will default to TLSv1.3.

**Important**  
Other versions of SSL and TLS are not supported.

For more information about using HTTPS with CloudFront, see [Use HTTPS with CloudFront](using-https.md). 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](secure-connections-supported-viewer-protocols-ciphers.md).

### GET requests that include a body
<a name="RequestCustom-get-body"></a>

If a viewer `GET` request includes a body, CloudFront returns an HTTP status code 403 (Forbidden) to the viewer.

### HTTP methods
<a name="RequestCustomHTTPMethods"></a>

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`

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)
<a name="request-custom-headers-behavior"></a>

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


| Header | Behavior if you don't configure CloudFront to cache based on header values | Caching based on header values is supported | 
| --- | --- | --- | 
|  Other-defined headers  |  **Legacy cache settings** – CloudFront forwards the headers to your origin.  |  Yes  | 
|  `Accept`  |  CloudFront removes the header.  |  Yes  | 
|  `Accept-Charset`  |  CloudFront removes the header.  |  Yes  | 
|  `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](cache-key-understand-cache-policy.md#cache-policy-compressed-objects) and [Serve compressed files](ServingCompressedFiles.md).  |  Yes  | 
|  `Accept-Language`  |  CloudFront removes the header.  |  Yes  | 
|  `Authorization`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html)  |  Yes  | 
|  `Cache-Control`  |  CloudFront forwards the header to your origin.  |  No  | 
|  `CloudFront-Forwarded-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](header-caching.md#header-caching-web-protocol).  |  Yes  | 
|  `CloudFront-Is-Desktop-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](header-caching.md#header-caching-web-device).  |  Yes  | 
|  `CloudFront-Is-Mobile-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](header-caching.md#header-caching-web-device).  |  Yes  | 
|  `CloudFront-Is-Tablet-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](header-caching.md#header-caching-web-device).  |  Yes  | 
|  `CloudFront-Viewer-Country`  |  CloudFront does not add the header before forwarding the request to your origin.  |  Yes  | 
|  `Connection`  |  CloudFront replaces this header with `Connection: Keep-Alive` before forwarding the request to your origin.  |  No  | 
|  `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, 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](Cookies.md).  |  No  | 
|  `Date`  |  CloudFront forwards the header to your origin.  |  Yes, but not recommended  | 
|  `Expect`  |  CloudFront removes the header.  |  Yes  | 
|  `From`  |  CloudFront forwards the header to your origin.  |  Yes  | 
|  `Host`  |  CloudFront sets the value to the domain name of the origin that is associated with the requested object. You can't cache based on the Host header for Amazon S3 or MediaStore origins.  |  Yes (custom) 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-Since`  |  CloudFront forwards the header to your origin.  |  Yes  | 
|  `Max-Forwards`  |  CloudFront forwards the header to your origin.  |  No  | 
|  `Origin`  |  CloudFront forwards the header to your origin.  |  Yes  | 
|  `Pragma`  |  CloudFront forwards the header to your origin.  |  No  | 
|  `Proxy-Authenticate`  |  CloudFront removes the header.  |  No  | 
|  `Proxy-Authorization`  |  CloudFront removes the header.  |  No  | 
|  `Proxy-Connection`  |  CloudFront removes the header.  |  No  | 
|  `Range`  |  CloudFront forwards the header to your origin. For more information, see [How CloudFront processes partial requests for an object (range GETs)](RangeGETs.md).  |  Yes, by default  | 
|  `Referer`  |  CloudFront removes the header.  |  Yes  | 
|  `Request-Range`  |  CloudFront forwards the header to your origin.  |  No  | 
|  `TE`  |  CloudFront removes the header.  |  No  | 
|  `Trailer`  |  CloudFront removes the header.  |  No  | 
|  `Transfer-Encoding`  |  CloudFront forwards the header to your origin.  |  No  | 
|  `Upgrade`  |  CloudFront removes the header, unless you've established a WebSocket connection.  |  No (except for WebSocket connections)  | 
|  `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](header-caching.md#header-caching-web-device).  |  Yes, but not recommended  | 
|  `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.  |  No  | 
|  `X-Edge-*`  |  CloudFront removes all `X-Edge-*` headers.  |  No  | 
|  `X-Forwarded-For`  |  CloudFront forwards the header to your origin. For more information, see [Client IP addresses](#RequestCustomIPAddresses).  |  Yes  | 
|  `X-Forwarded-Proto`  |  CloudFront removes the header.  |  No  | 
|  `X-HTTP-Method-Override`  |  CloudFront removes the header.  |  Yes  | 
|  `X-Real-IP`  |  CloudFront removes the header.  |  No  | 

### HTTP version
<a name="RequestCustomHTTPVersion"></a>

CloudFront forwards requests to your custom origin using HTTP/1.1.

### Maximum length of a request and maximum length of a URL
<a name="RequestCustomMaxRequestStringLength"></a>

The maximum length of a request, including the path, the query string (if any), and headers, is 32,768 bytes.

CloudFront constructs a URL from the request. The maximum length of this URL is 8192 bytes.

If a URL exceeds the maximum length, CloudFront returns HTTP status code 414 (URI Too Long) to the viewer. If a request exceeds the maximum length because the header size is exceeded, CloudFront returns HTTP status code 494 to the viewer. In both cases, CloudFront then terminates the TCP connection to the viewer.

### OCSP stapling
<a name="request-custom-ocsp-stapling"></a>

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 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
<a name="request-custom-persistent-connections"></a>

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)](DownloadDistValuesOrigin.md#DownloadDistValuesOriginKeepaliveTimeout) in the section [All distribution settings reference](distribution-web-values-specify.md).

### Protocols
<a name="RequestCustomProtocols"></a>

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.

**Important**  
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](HowToUpdateDistribution.md). For information about how to update a distribution using the CloudFront API, go to [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html) in the *Amazon CloudFront API Reference*. 

### Query strings
<a name="RequestCustomQueryStrings"></a>

You can configure whether CloudFront forwards query string parameters to your origin. For more information, see [Cache content based on query string parameters](QueryStringParameters.md).

### Origin connection timeout and attempts
<a name="custom-origin-timeout-attempts"></a>

*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](high_availability_origin_failover.md#controlling-attempts-and-timeouts).

### Origin response timeout
<a name="request-custom-request-timeout"></a>

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 or stops responding within the duration of the response timeout, CloudFront drops the connection. If the specified number of [origin connection attempts](DownloadDistValuesOrigin.md#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](DownloadDistValuesOrigin.md#DownloadDistValuesOriginResponseTimeout).

### Simultaneous requests for the same object (request collapsing)
<a name="request-custom-traffic-spikes"></a>

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 [CloudFront and edge function logging](logging.md).

CloudFront only collapses requests that share a [*cache key*](understanding-the-cache-key.md). 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](using-managed-cache-policies.md).

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](controlling-the-cache-key.md), the [origin request policy](controlling-origin-requests.md), or the legacy cache settings.

### `User-Agent` header
<a name="request-custom-user-agent-header"></a>

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

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. 

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
<a name="ResponseBehaviorCustomOrigin"></a>

Learn how CloudFront processes responses from your custom origin.

**Contents**
+ [`100 Continue` responses](#Response100Continue)
+ [Caching](#ResponseCustomCaching)
+ [Canceled requests](#response-custom-canceled-requests)
+ [Content negotiation](#ResponseCustomContentNegotiation)
+ [Cookies](#ResponseCustomCookies)
+ [Dropped TCP connections](#ResponseCustomDroppedTCPConnections)
+ [HTTP response headers that CloudFront removes or replaces](#ResponseCustomRemovedHeaders)
+ [Maximum cacheable file size](#ResponseCustomMaxFileSize)
+ [Origin unavailable](#ResponseCustomOriginUnavailable)
+ [Redirects](#ResponseCustomRedirects)
+ [`Transfer-Encoding` header](#ResponseCustomTransferEncoding)

### `100 Continue` responses
<a name="Response100Continue"></a>

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
<a name="ResponseCustomCaching"></a>
+ Ensure that the origin server sets valid and accurate values for the `Date` and `Last-Modified` header fields.
+ 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)](#request-custom-traffic-spikes).

### Canceled requests
<a name="response-custom-canceled-requests"></a>

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
<a name="ResponseCustomContentNegotiation"></a>

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](#ResponseCustomRemovedHeaders).

### Cookies
<a name="ResponseCustomCookies"></a>

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

### Dropped TCP connections
<a name="ResponseCustomDroppedTCPConnections"></a>

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.
+ **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
<a name="ResponseCustomRemovedHeaders"></a>

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](Cookies.md).
+ `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](header-caching.md#header-caching-web-device).
  + 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](#ResponseCustomContentNegotiation).
  + 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
<a name="ResponseCustomMaxFileSize"></a>

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](RangeGETs.md#cache-large-objects-with-range-requests).

### Origin unavailable
<a name="ResponseCustomOriginUnavailable"></a>

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](HTTPStatusCodes.md#HTTPStatusCodes-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
<a name="ResponseCustomRedirects"></a>

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 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
<a name="ResponseCustomTransferEncoding"></a>

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](#ResponseCustomDroppedTCPConnections). 

# Request and response behavior for origin groups
<a name="RequestAndResponseBehaviorOriginGroups"></a>

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](RequestAndResponseBehaviorS3Origin.md) and [Request and response behavior for custom origins](RequestAndResponseBehaviorCustomOrigin.md).

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

# Add custom headers to origin requests
<a name="add-origin-custom-headers"></a>

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](#add-origin-custom-headers-use-cases)
+ [Configure CloudFront to add custom headers to origin requests](#add-origin-custom-headers-configure)
+ [Custom headers that CloudFront can’t add to origin requests](#add-origin-custom-headers-denylist)
+ [Configure CloudFront to forward the `Authorization` header](#add-origin-custom-headers-forward-authorization)

## Use cases
<a name="add-origin-custom-headers-use-cases"></a>

You can use custom headers, such as the following examples:

**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.  
If you’re using an Amazon S3 origin and you enable [Amazon S3 server access logging](https://docs.aws.amazon.com/AmazonS3/latest/dev/ServerLogs.html), 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](header-caching.md#header-caching-web-cors).

**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](private-content-overview.md#forward-custom-headers-restrict-access).

## Configure CloudFront to add custom headers to origin requests
<a name="add-origin-custom-headers-configure"></a>

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](DownloadDistValuesOrigin.md#DownloadDistValuesOriginCustomHeaders).
+ **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](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html) or [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html) 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](cloudfront-limits.md#limits-custom-headers).

## Custom headers that CloudFront can’t add to origin requests
<a name="add-origin-custom-headers-denylist"></a>

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`
+ `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
<a name="add-origin-custom-headers-forward-authorization"></a>

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](controlling-the-cache-key.md).
+ 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](using-managed-origin-request-policies.md).

# How CloudFront processes partial requests for an object (range GETs)
<a name="RangeGETs"></a>

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.

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](https://httpwg.org/specs/rfc7233.html#range.requests) in RFC 7233, or [Range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range) in the MDN Web Docs.

## Use range requests to cache large objects
<a name="cache-large-objects-with-range-requests"></a>

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](cloudfront-limits.md#limits-web-distributions). 

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

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

1. When the viewer has received all of the parts, it can combine them to construct the original 100 GB object. 

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

# How CloudFront processes HTTP 3xx status codes from your origin
<a name="http-3xx-status-codes"></a>

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)

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

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
<a name="HTTPStatusCodes"></a>

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](RequestAndResponseBehaviorCustomOrigin.md#ResponseCustomOriginUnavailable).

If you have enabled logging, CloudFront writes the results to the logs regardless of the HTTP status code.

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](DownloadDistValuesErrorPages.md). 
+ For information about the error caching minimum TTL in the CloudFront console, see [Error caching minimum TTL (seconds)](DownloadDistValuesErrorPages.md#DownloadDistValuesErrorCachingMinTTL).
+ For a list of the HTTP status codes that CloudFront caches, see [HTTP 4xx and 5xx status codes that CloudFront caches](#HTTPStatusCodes-cached-errors).

**Topics**
+ [How CloudFront processes errors when you have configured custom error pages](#HTTPStatusCodes-custom-error-pages)
+ [How CloudFront processes errors if you haven't configured custom error pages](#HTTPStatusCodes-no-custom-error-pages)
+ [HTTP 4xx and 5xx status codes that CloudFront caches](#HTTPStatusCodes-cached-errors)

## How CloudFront processes errors when you have configured custom error pages
<a name="HTTPStatusCodes-custom-error-pages"></a>

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
<a name="HTTPStatusCodes-custom-error-pages-not-in-cache"></a>

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](#HTTPStatusCodes-cached-errors).
  + Your origin returns an HTTP 4xx status code with 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](#HTTPStatusCodes-cached-errors-with-cache-control).

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

1. CloudFront finds the first cache behavior in your distribution that has a path pattern that matches the path of the custom error page.

1. The CloudFront edge location sends a request for the custom error page to the origin that is specified in the cache behavior.

1. The origin returns the custom error page to the edge location.

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

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

**Note**  
If you also configured a cache behavior for the same custom error page, CloudFront uses the cache behavior TTL instead. In this case, CloudFront will do the following for steps 5 and 6:  
After CloudFront returns the custom error page to the viewer that made the request, CloudFront checks the cache behavior TTL (for example, you set the default TTL to 5 seconds). CloudFront then caches the custom error page up to that maximum.
After 5 seconds elapse, CloudFront fetches the custom error page from the origin again. CloudFront will continue to retry at intervals specified by the cache behavior TTL.
For more information, see the cache behavior [TTL settings](DownloadDistValuesCacheBehavior.md#DownloadDistValuesMinTTL).

### The requested object is in the edge cache
<a name="HTTPStatusCodes-custom-error-pages-in-cache"></a>

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.

**CloudFront does the following:**

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. 

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

## How CloudFront processes errors if you haven't configured custom error pages
<a name="HTTPStatusCodes-no-custom-error-pages"></a>

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](#HTTPStatusCodes-no-custom-error-pages-not-in-cache)
+ [The requested object is in the edge cache](#HTTPStatusCodes-no-custom-error-pages-in-cache)

### The requested object is not in the edge cache
<a name="HTTPStatusCodes-no-custom-error-pages-not-in-cache"></a>

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](#HTTPStatusCodes-cached-errors)
  + Your origin returns an HTTP 4xx status code with 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](#HTTPStatusCodes-cached-errors-with-cache-control).

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

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

1. 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
<a name="HTTPStatusCodes-no-custom-error-pages-in-cache"></a>

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:

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. 

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

**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](Expiration.md#stale-content). 
CloudFront will only serve an object that is stale up to the specified [maximum TTL](DownloadDistValuesCacheBehavior.md#DownloadDistValuesMaxTTL) value. After this duration, the object won't be available from the edge cache.

## HTTP 4xx and 5xx status codes that CloudFront caches
<a name="HTTPStatusCodes-cached-errors"></a>

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](using-managed-cache-policies.md#managed-cache-policy-caching-disabled) managed cache policy, CloudFront won't cache these status codes or custom error pages.


|  |  | 
| --- |--- |
|  404  |  Not Found  | 
|  414  |  Request-URI Too Large  | 
|  500  |  Internal Server Error  | 
|  501  |  Not Implemented  | 
|  502  |  Bad Gateway  | 
|  503  |  Service Unavailable  | 
|  504  |  Gateway Time-out  | 

### HTTP 4xx status codes that CloudFront caches based on `Cache-Control` headers
<a name="HTTPStatusCodes-cached-errors-with-cache-control"></a>

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  |  Bad Request  | 
|  403  |  Forbidden  | 
|  405  |  Method Not Allowed  | 
|  412¹  |  Precondition Failed  | 
|  415¹  |  Unsupported Media Type  | 

¹CloudFront doesn't support creating custom error pages for these HTTP status codes.

# Generate custom error responses
<a name="GeneratingCustomErrorResponses"></a>

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

**Topics**
+ [Configure error response behavior](custom-error-pages-procedure.md)
+ [Create a custom error page for specific HTTP status codes](creating-custom-error-pages.md)
+ [Store objects and custom error pages in different locations](custom-error-pages-different-locations.md)
+ [Change response codes returned by CloudFront](custom-error-pages-response-code.md)
+ [Control how long CloudFront caches errors](custom-error-pages-expiration.md)

# Configure error response behavior
<a name="custom-error-pages-procedure"></a>

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 CloudFormation. Regardless of how you choose to update the configuration, consider the following tips and recommendations:
+ 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](custom-error-pages-different-locations.md). 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](custom-error-pages-different-locations.md).
+ 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)](private-content-restricting-access-to-s3.md). 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](custom-error-pages-expiration.md).

## Configure custom error responses
<a name="custom-error-pages-console"></a>

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 CloudFront standard distribution](GettingStarted.SimpleDistribution.md).

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

1. In the list of distributions, choose the distribution to update.

1. Choose the **Error Pages** tab, then choose **Create Custom Error Response**.

1. Enter the applicable values. For more information, see [Custom error pages and error caching](DownloadDistValuesErrorPages.md).

1. After entering the desired values, choose **Create**.

------
#### [ CloudFront API or CloudFormation ]

To configure custom error responses with the CloudFront API or CloudFormation, use the `CustomErrorResponse` type in a distribution. For more information, see the following:
+ [AWS::CloudFront::Distribution CustomErrorResponse](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-customerrorresponse.html) in the *AWS CloudFormation User Guide*
+ [CustomErrorResponse](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CustomErrorResponse.html) in the *Amazon CloudFront API Reference*

------

# Create a custom error page for specific HTTP status codes
<a name="creating-custom-error-pages"></a>

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](custom-error-pages-procedure.md).

For example, the following is a custom error page:

![\[Screenshot of an example custom AWS 404 page.\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/images/custom-error-page-aws-404-example.png)


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](custom-error-pages-response-code.md). 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:  
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](HTTPStatusCodes.md).

# Store objects and custom error pages in different locations
<a name="custom-error-pages-different-locations"></a>

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

# Change response codes returned by CloudFront
<a name="custom-error-pages-response-code"></a>

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.
+ 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](AccessLogs.md) 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
<a name="custom-error-pages-expiration"></a>

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](HTTPStatusCodes.md#HTTPStatusCodes-cached-errors).) 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.

**Note**  
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](custom-error-pages-response-code.md).) 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 for the cache behavior for which the error page is being fetched.

If the origin adds a `Cache-Control: no-store`, `Cache-Control: no-cache`, or `Cache-Control: private` directive for error codes 404, 410, 414, or 501, CloudFront does not cache the error response. For all other error codes, CloudFront ignores the `no-store`, `no-cache`, and `private` directives and caches the error response for the value of **Error Caching Minimum TTL**.

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

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.