

# Troubleshooting error response status codes in CloudFront
<a name="troubleshooting-response-errors"></a>

If CloudFront requests an object from your origin, and the origin returns an HTTP 4xx or 5xx status code, there's a problem with communication between CloudFront and your origin. 

This topic also includes troubleshooting steps for these status codes when using Lambda@Edge or CloudFront Functions.

The following topics provide detailed explanations of the potential causes behind these error responses and offers step-by-step guidance on how to diagnose and resolve the underlying issues.

**Topics**
+ [HTTP 400 status code (Bad Request)](http-400-bad-request.md)
+ [HTTP 401 status code (Unauthorized)](http-401-unauthorized.md)
+ [HTTP 403 status code (Invalid method)](http-403-invalid-method.md)
+ [HTTP 403 status code (Permission Denied)](http-403-permission-denied.md)
+ [HTTP 404 status code (Not Found)](http-404-not-found.md)
+ [HTTP 412 status code (Precondition Failed)](http-412-precondition-failed.md)
+ [HTTP 500 status code (Internal Server Error)](http-500-internal-server-error.md)
+ [HTTP 502 status code (Bad Gateway)](http-502-bad-gateway.md)
+ [HTTP 503 status code (Service Unavailable)](http-503-service-unavailable.md)
+ [HTTP 504 status code (Gateway Timeout)](http-504-gateway-timeout.md)

# HTTP 400 status code (Bad Request)
<a name="http-400-bad-request"></a>

CloudFront returns a 400 bad request when the client sends some invalid data in the request such as missing or incorrect content in the payload or parameters. This could also represent a generic client error.

## Amazon S3 origin returns a 400 error
<a name="s3-origin-400-error"></a>

If you're using an Amazon S3 origin with your CloudFront distribution, your distribution might send error responses with HTTP status code 400 Bad Request, and a message similar to the following:

*The authorization header is malformed; the region '*<AWS Region>*' is wrong; expecting '*<AWS Region>*'*

For example:

*The authorization header is malformed; the region 'us-east-1' is wrong; expecting 'us-west-2'*

This problem can occur in the following scenario:

1. Your CloudFront distribution's origin is an Amazon S3 bucket.

1. You moved the S3 bucket from one AWS Region to another. That is, you deleted the S3 bucket, then later you created a new bucket with the same bucket name, but in a different AWS Region than where the original S3 bucket was located.

To fix this error, update your CloudFront distribution so that it finds the S3 bucket in the bucket's current AWS Region.

**To update your CloudFront distribution**

1. Sign in to the AWS Management Console and open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose the distribution that produces this error.

1. Choose **Origins and Origin Groups**.

1. Find the origin for the S3 bucket that you moved. Select the check box next to this origin, then choose **Edit**.

1. Choose **Yes, Edit**. You do not need to change any settings before choosing **Yes, Edit**.

When you complete these steps, CloudFront redeploys your distribution. While the distribution is deploying, you see the **Deploying** status under the **Last modified** column. Some time after the deployment is complete, you should stop receiving the `AuthorizationHeaderMalformed` error responses.

## Application Load Balancer origin returns a 400 error
<a name="alb-origin-400-error"></a>

If you're using an Application Load Balancer origin with your CloudFront distribution, possible causes of a 400 error include the following:
+ The client sent a malformed request that does not meet the HTTP specification.
+ The request header exceeds 16 KB per request line, 16 KB per single header, or 64 KB for the entire request header.
+ The client closed the connection before sending the full request body.

# HTTP 401 status code (Unauthorized)
<a name="http-401-unauthorized"></a>

A 401 Unauthorized response status code indicates that the client request hasn't been completed because it lacks valid authentication credentials for the requested resource. This status code is sent with an HTTP `WWW-Authenticate` response header that contains information about how the client can request the resource again after prompting the user for authentication credentials. For more information, see [401 Unauthorized](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401).

In CloudFront, if your origin expects an `Authorization` header to authenticate the requests, CloudFront needs to forward the `Authorization` header to the origin to avoid a 401 Unauthorized error. 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 by 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 can't 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 the managed `AllViewer` origin request policy for this use case. For more information, see [Use managed origin request policies](using-managed-origin-request-policies.md).

For more information, see [How can I configure CloudFront to forward the Authorization header to the origin?](https://repost.aws/knowledge-center/cloudfront-authorization-header)

# HTTP 403 status code (Invalid method)
<a name="http-403-invalid-method"></a>

CloudFront returns a 403 (Invalid method) error if you're trying to use an HTTP method that you haven't specified in the CloudFront distribution. You can specify one of the following options for your distribution:
+ CloudFront forwards only `GET` and `HEAD` requests.
+ CloudFront forwards only `GET`, `HEAD`, and `OPTIONS` requests.
+ CloudFront forwards `GET`, `HEAD`, `OPTIONS`, `PUT`, `PATCH`, `POST`, and `DELETE` requests. (If you select this option, you might need to restrict access to your Amazon S3 bucket or custom origin so that users can't perform operations that you don't want them to. For example, you might not want users to have permissions to delete objects from your origin.

# HTTP 403 status code (Permission Denied)
<a name="http-403-permission-denied"></a>

An HTTP 403 error means the client isn't authorized to access the requested resource. The client understands the request, but can't authorize viewer access. The following are common causes when CloudFront returns this status code:

**Topics**
+ [Alternate CNAME is incorrectly configured](#alternate-cname-incorrectly-configured)
+ [AWS WAF is configured on CloudFront distribution or at the origin](#aws-waf-configured-on-distribution-origin)
+ [Custom origin returns a 403 error](#custom-origin-returning-403)
+ [Amazon S3 origin returns a 403 error](#s3-origin-403-error)
+ [Geographic restrictions return a 403 error](#geolocation-403)
+ [Signed URL or signed cookie configuration returns a 403 error](#signed-URLs-cookies-403)
+ [Stacked distributions cause a 403 error](#stacked-distributions-403)

## Alternate CNAME is incorrectly configured
<a name="alternate-cname-incorrectly-configured"></a>

Verify that you specified the correct CNAME for our distribution. To use an alternate CNAME instead of the default CloudFront URL:

1. Create a CNAME record in your DNS to point the CNAME to CloudFront distribution URL.

1. Add the CNAME in your CloudFront distribution configuration.

If you create the DNS record but don't add the CNAME in your CloudFront distribution configuration, then the request returns a 403 error. For more information about configuring a custom CNAME, see [Use custom URLs by adding alternate domain names (CNAMEs)](CNAMEs.md).

## AWS WAF is configured on CloudFront distribution or at the origin
<a name="aws-waf-configured-on-distribution-origin"></a>

When AWS WAF sits between the client and CloudFront, CloudFront can't distinguish between a 403 error code that’s returned by your origin and a 403 error code that's returned by AWS WAF when a request is blocked.

To find the source of the 403 status code, check your AWS WAF web access control list (ACL) rule for a blocked request. For more information, see the following topics:
+ [AWS WAF web access control lists (web ACLs)](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl.html)
+ [Testing and tuning your AWS WAF protections](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-testing.html)

## Custom origin returns a 403 error
<a name="custom-origin-returning-403"></a>

If you're using a custom origin, you might see a 403 error if you have a custom firewall configuration at the origin. To troubleshoot, make the request directly to the origin. If you can replicate the error without CloudFront, then the origin is causing the 403 error. 

If the custom origin is causing the error, check the origin logs to identify what might be causing the error. For more information, see the following troubleshooting topics:
+ [How do I troubleshoot HTTP 403 errors from API Gateway?](https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-troubleshoot-403-forbidden/ )
+ [How do I troubleshoot Application Load Balancer HTTP 403 forbidden errors?](https://repost.aws/knowledge-center/alb-http-403-error)

## Amazon S3 origin returns a 403 error
<a name="s3-origin-403-error"></a>

You might see a 403 error for the following reasons:
+ CloudFront doesn't have access to the Amazon S3 bucket. This can happen if origin access identity (OAI) or origin access control (OAC) isn't enabled for your distribution and the bucket is private.
+ The specified path in the requested URL isn't correct.
+ The requested object doesn't exist.
+ The host header was forwarded with the REST API endpoint. For more information, see [HTTP Host header bucket specification](https://docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html#VirtualHostingSpecifyBucket) in the *Amazon Simple Storage Service User Guide*.
+ You configured custom error pages. For more information, see [How CloudFront processes errors when you have configured custom error pages](HTTPStatusCodes.md#HTTPStatusCodes-custom-error-pages).

## Geographic restrictions return a 403 error
<a name="geolocation-403"></a>

If you enabled geographic restrictions (also known as geoblocking) to prevent users in specific geographic locations from accessing content that you're distributing through a CloudFront distribution, blocked users receive a 403 error.

For more information, see [Restrict the geographic distribution of your content](georestrictions.md).

## Signed URL or signed cookie configuration returns a 403 error
<a name="signed-URLs-cookies-403"></a>

If you enabled **Restrict viewer access** for your distribution's behavior configuration, then requests that don't use signed cookies or signed URLs result in a 403 error. For more information, see the following topics:
+ [Serve private content with signed URLs and signed cookies](PrivateContent.md)
+ [How do I troubleshoot issues related to a signed URL or signed cookies in CloudFront?](https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-troubleshoot-signed-url-cookies/)

## Stacked distributions cause a 403 error
<a name="stacked-distributions-403"></a>

If you have two or more distributions within a chain of requests to the origin endpoint, CloudFront returns a 403 error. We don't recommend placing one distribution in front of another.

# HTTP 404 status code (Not Found)
<a name="http-404-not-found"></a>

CloudFront returns a 404 (Not Found) error when the client attempts to access a resource that doesn’t exist. If you receive this error with your CloudFront distribution, common causes include the following:
+ Resource doesn't exist.
+ URL is incorrect.
+ Custom origin returning a 404.
+ Custom error pages returning a 404. (Any error code might be translated to 404.) For more information, see [How CloudFront processes errors when you have configured custom error pages](HTTPStatusCodes.md#HTTPStatusCodes-custom-error-pages).
+ Custom error page accidentally deleted, resulting in a 404 because the request looks for the deleted custom error page. For more information, see [How CloudFront processes errors if you haven't configured custom error pages](HTTPStatusCodes.md#HTTPStatusCodes-no-custom-error-pages).
+ Incorrect origin path. If the origin path is populated, its value is appended to the path of each request from the browser before the request is forwarded to the origin. For more information, see [Origin path](DownloadDistValuesOrigin.md#DownloadDistValuesOriginPath).

# HTTP 412 status code (Precondition Failed)
<a name="http-412-precondition-failed"></a>

CloudFront returns a 412 (Precondition Failed) error code when access to the target resource has been denied. In some cases, a server is configured to accept requests only after certain conditions are fulfilled. If any of the specified conditions are not met, then the server doesn't allow the client to access the given resource. Instead, the server responds with a 412 error code.

Common causes of a 412 error in CloudFront include:
+ Conditional requests on methods other than `GET` or `HEAD` when the condition defined by the `If-Unmodified-Since` or `If-None-Match` headers is not fulfilled. In that case, the request, usually an upload or a modification of a resource, can't be made.
+ A condition in one or more of the request fields in the CloudFront [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html) API operation evaluates as false.

# HTTP 500 status code (Internal Server Error)
<a name="http-500-internal-server-error"></a>

An HTTP 500 status code (Internal Server Error) indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. The following are some common causes of 500 errors in Amazon CloudFront.

**Topics**
+ [Origin server returns 500 error to CloudFront](#origin-server-500-error)

## Origin server returns 500 error to CloudFront
<a name="origin-server-500-error"></a>

Your origin server might be returning a 500 error to CloudFront. Refer to the following troubleshooting topics for more information:
+ **If Amazon S3 returns a 500 error**, see [How do I troubleshoot a HTTP 500 or 503 error from Amazon S3?](https://repost.aws/knowledge-center/http-5xx-errors-s3)
+ **If API Gateway returns a 500 error**, see [How do I troubleshoot 5xx errors for API Gateway REST API?](https://repost.aws/knowledge-center/api-gateway-5xx-error).
+ **If Elastic Load Balancing returns a 500 error**, see [HTTP 500: Internal server error](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-troubleshooting.html#http-500-issues) in the *User Guide for Application Load Balancers*.

If the preceding list doesn't resolve the 500 error, the issue might be with a CloudFront Point of Presence returning an internal server error. You can contact [Support](https://console.aws.amazon.com/support/home#/) for assistance.

# HTTP 502 status code (Bad Gateway)
<a name="http-502-bad-gateway"></a>

CloudFront returns a HTTP 502 status code (Bad Gateway) when CloudFront wasn't able to serve the requested object because it couldn't connect to the origin server. 

If you're using Lambda@Edge, the issue might be a Lambda validation error. If you receive an HTTP 502 error with the `NonS3OriginDnsError` error code, there's likely a DNS configuration problem that's preventing CloudFront from connecting to the origin.

**Topics**
+ [SSL/TLS negotiation failure between CloudFront and a custom origin server](#ssl-negotitation-failure)
+ [Origin is not responding with supported ciphers/protocols](#origin-not-responding-with-supported-ciphers-protocols)
+ [SSL/TLS certificate on the origin is expired, invalid, self-signed, or the certificate chain is in the wrong order](#ssl-certificate-expired)
+ [Origin is not responding on specified ports in origin settings](#origin-not-responding-on-specified-ports)
+ [Lambda validation error](#http-502-lambda-validation-error)
+ [CloudFront function validation error](#http-502-cloudfront-function-validation-error)
+ [DNS error (`NonS3OriginDnsError`)](#http-502-dns-error)
+ [Application Load Balancer origin 502 error](#cloudfront-alb-502-error)
+ [API Gateway origin 502 error](#cloudfront-api-gateway-502-error)

## SSL/TLS negotiation failure between CloudFront and a custom origin server
<a name="ssl-negotitation-failure"></a>

If you use a custom origin that requires HTTPS between CloudFront and your origin, mismatched domain names might cause errors. The SSL/TLS certificate on your origin *must* include a domain name that matches either the **Origin Domain** that you specified for the CloudFront distribution or the `Host` header of the origin request.

If the domain names don't match, the SSL/TLS handshake fails, and CloudFront returns an HTTP status code 502 (Bad Gateway) and sets the `X-Cache` header to `Error from cloudfront`.

To determine whether domain names in the certificate match the **Origin Domain** in the distribution or the `Host` header, you can use an online SSL checker or OpenSSL. If the domain names don't match, you have two options:
+ Get a new SSL/TLS certificate that includes the applicable domain names. 

  If you use AWS Certificate Manager (ACM), see [Requesting a public certificate](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-public.html) in the *AWS Certificate Manager User Guide* to request a new certificate.
+ Change the distribution configuration so CloudFront no longer tries to use SSL to connect with your origin.

### Online SSL checker
<a name="troubleshooting-ssl-negotiation-failure-online-ssl-checker"></a>

To find an SSL test tool, search the internet for "online ssl checker." Typically, you specify the name of your domain, and the tool returns a variety of information about your SSL/TLS certificate. Confirm that the certificate contains your domain name in the **Common Name** or **Subject Alternative Names** fields.

### OpenSSL
<a name="troubleshooting-ssl-negotiation-failure-openssl"></a>

To help troubleshoot HTTP 502 errors from CloudFront, you can use OpenSSL to try to make an SSL/TLS connection to your origin server. If OpenSSL is not able to make a connection, that can indicate a problem with your origin server's SSL/TLS configuration. If OpenSSL is able to make a connection, it returns information about the origin server's certificate, including the certificate's common name (`Subject CN` field) and subject alternative name (`Subject Alternative Name` field).

Use the following OpenSSL command to test the connection to your origin server (replace *origin domain* with your origin server's domain name, such as example.com):

`openssl s_client -connect origin domain name:443`

If the following are true:
+ Your origin server supports multiple domain names with multiple SSL/TLS certificates
+ Your distribution is configured to forward the `Host` header to the origin

Then add the `-servername` option to the OpenSSL command, as in the following example (replace *CNAME* with the CNAME that's configured in your distribution):

`openssl s_client -connect origin domain name:443 -servername CNAME`

## Origin is not responding with supported ciphers/protocols
<a name="origin-not-responding-with-supported-ciphers-protocols"></a>

CloudFront connects to origin servers using ciphers and protocols. For a list of the ciphers and protocols that CloudFront supports, see [Supported protocols and ciphers between CloudFront and the origin](secure-connections-supported-ciphers-cloudfront-to-origin.md). If your origin does not respond with one of these ciphers or protocols in the SSL/TLS exchange, CloudFront fails to connect. You can validate that your origin supports the ciphers and protocols by using an online tool such as [SSL Labs](https://www.ssllabs.com/ssltest). Type the domain name of your origin in the **Hostname** field, and then choose **Submit**. Review the **Common names** and **Alternative names** fields from the test to see if they match your origin's domain name. After the test is finished, find the **Protocols** and **Cipher Suites** sections in the test results to see which ciphers or protocols are supported by your origin. Compare them with the list of [Supported protocols and ciphers between CloudFront and the origin](secure-connections-supported-ciphers-cloudfront-to-origin.md).

## SSL/TLS certificate on the origin is expired, invalid, self-signed, or the certificate chain is in the wrong order
<a name="ssl-certificate-expired"></a>

If the origin server returns the following, CloudFront drops the TCP connection, returns HTTP status code 502 (Bad Gateway), and sets the `X-Cache` header to `Error from cloudfront`:
+ An expired certificate
+ Invalid certificate
+ Self-signed certificate
+ Certificate chain in the wrong order

**Note**  
If the full chain of certificates, including the intermediate certificate, is not present, CloudFront drops the TCP connection.

For information about installing an SSL/TLS certificate on your custom origin server, see [Require HTTPS for communication between CloudFront and your custom origin](using-https-cloudfront-to-custom-origin.md).

## Origin is not responding on specified ports in origin settings
<a name="origin-not-responding-on-specified-ports"></a>

When you create an origin on your CloudFront distribution, you can set the ports that CloudFront connects to the origin with for HTTP and HTTPS traffic. By default, these are TCP 80/443. You have the option to modify these ports. If your origin is rejecting traffic on these ports for any reason, or if your backend server isn't responding on the ports, CloudFront will fail to connect.

To troubleshoot these issues, check any firewalls running in your infrastructure and validate that they are not blocking the supported IP ranges. For more information, see [AWS IP address ranges](https://docs.aws.amazon.com/vpc/latest/userguide/aws-ip-ranges.html) in the *Amazon VPC User Guide*. Additionally, verify whether your web server is running on the origin.

## Lambda validation error
<a name="http-502-lambda-validation-error"></a>

If you're using Lambda@Edge, an HTTP 502 status code can indicate that your Lambda function response was incorrectly formed or included invalid content. For more information about troubleshooting Lambda@Edge errors, see [Test and debug Lambda@Edge functions](lambda-edge-testing-debugging.md).

## CloudFront function validation error
<a name="http-502-cloudfront-function-validation-error"></a>

If you're using CloudFront functions, an HTTP 502 status code can indicate that the CloudFront function is trying to add, delete, or change a read-only header. This error does not show up during testing, but will show up after you deploy the function and run the request. To resolve this error, check and update your CloudFront function. For more information, see [Update functions](update-function.md).

## DNS error (`NonS3OriginDnsError`)
<a name="http-502-dns-error"></a>

An HTTP 502 error with the `NonS3OriginDnsError` error code indicates that there's a DNS configuration problem that prevents CloudFront from connecting to the origin. If you get this error from CloudFront, make sure that the origin's DNS configuration is correct and working.

When CloudFront receives a request for an object that's expired or is not in its cache, it makes a request to the origin to get the object. To make a successful request to the origin, CloudFront performs a DNS resolution on the origin domain. If the DNS service for your domain is experiencing issues, CloudFront can't resolve the domain name to get the IP address, which results in an HTTP 502 error (`NonS3OriginDnsError`). To fix this problem, contact your DNS provider, or, if you are using Amazon Route 53, see [Why can't I access my website that uses Route 53 DNS services?](https://aws.amazon.com/premiumsupport/knowledge-center/route-53-dns-website-unreachable/)

To further troubleshoot this issue, ensure that the [authoritative name servers](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/route-53-concepts.html#route-53-concepts-authoritative-name-server) of your origin's root domain or zone apex (such as `example.com`) are functioning correctly. You can use the following commands to find the name servers for your apex origin, with a tool such as [dig](https://en.wikipedia.org/wiki/Dig_(command)) or [nslookup](https://en.wikipedia.org/wiki/Nslookup):

```
dig OriginAPEXDomainName NS +short
```

```
nslookup -query=NS OriginAPEXDomainName
```

When you have the names of your name servers, use the following commands to query the domain name of your origin against them to make sure that each responds with an answer:

```
dig OriginDomainName @NameServer
```

```
nslookup OriginDomainName NameServer
```

**Important**  
Make sure that you perform this DNS troubleshooting using a computer that's connected to the public internet. CloudFront resolves the origin domain using public DNS on the internet, so it's important to troubleshoot in a similar context.

If your origin is a subdomain whose DNS authority is delegated to a different name server than the root domain, make sure that the name server (`NS`) and start of authority (`SOA`) records are configured correctly for the subdomain. You can check for these records using commands similar to the preceding examples.

For more information about DNS, see [Domain Name System (DNS) concepts](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/route-53-concepts.html#route-53-concepts-domain-name-system-dns) in the Amazon Route 53 documentation.

## Application Load Balancer origin 502 error
<a name="cloudfront-alb-502-error"></a>

If you use Application Load Balancer as your origin and receive a 502 error, see [How do I troubleshoot Application Load Balancer HTTP 502 errors?](https://repost.aws/knowledge-center/elb-alb-troubleshoot-502-errors).

## API Gateway origin 502 error
<a name="cloudfront-api-gateway-502-error"></a>

If you use API Gateway and receive a 502 error, see [How do I resolve HTTP 502 errors from API Gateway REST APIs with Lambda proxy integration?](https://repost.aws/knowledge-center/malformed-502-api-gateway).

# HTTP 503 status code (Service Unavailable)
<a name="http-503-service-unavailable"></a>

An HTTP 503 status code (Service Unavailable) typically indicates a performance issue on the origin server. In rare cases, it indicates that CloudFront temporarily can't satisfy a request because of resource constraints at an edge location.

If you are using Lambda@Edge or CloudFront Functions, the issue might be an execution error or a Lambda@Edge limit exceeded error.

**Topics**
+ [Origin server does not have enough capacity to support the request rate](#http-503-service-unavailable-not-enough-origin-capacity)
+ [CloudFront caused the error due to resource constraints at the edge location](#http-503-service-unavailable-limited-resources-at-edge-location)
+ [Lambda@Edge or CloudFront Function execution error](#http-503-lambda-execution-error)
+ [Lambda@Edge limit exceeded](#http-503-lambda-limit-exceeded-error)

## Origin server does not have enough capacity to support the request rate
<a name="http-503-service-unavailable-not-enough-origin-capacity"></a>

When an origin server is unavailable or unable to serve incoming requests, it returns an HTTP 503 status code (Service Unavailable). CloudFront then relays the error back to the user. To resolve this issue, try the following solutions:
+ **If you use Amazon S3 as your origin server**:
  + You can send 3,500 PUT/COPY/POST/DELETE or 5,500 GET/HEAD requests per second per partitioned Amazon S3 prefix. When Amazon S3 returns a 503 Slow Down response, this typically indicates an excessive request rate against a specific Amazon S3 prefix.

    Because request rates apply per prefix in an S3 bucket, objects should be distributed across multiple prefixes. As the request rate on the prefixes gradually increases, Amazon S3 scales up to handle requests for each of the prefixes separately. As a result, the overall request rate that the bucket handles is a multiple of the number of prefixes.
  + For more information, see [Optimizing Amazon S3 performance](https://docs.aws.amazon.com/AmazonS3/latest/userguide/optimizing-performance.html) in the *Amazon Simple Storage Service User Guide*.
+ **If you use Elastic Load Balancing as your origin server**:
  + Make sure that your backend instances can respond to health checks.
  + Make sure that your load balancer and backend instances can handle the load.

  For more information, see:
  + [How do I troubleshoot 503 errors returned while using Classic Load Balancer?](https://repost.aws/knowledge-center/503-error-classic)
  + [How do I troubleshoot 503 (service unavailable) errors from my Application Load Balancer?](https://repost.aws/knowledge-center/alb-troubleshoot-503-errors)
+ **If you use a custom origin**:
  + Examine the application logs to ensure that your origin has sufficient resources, such as memory, CPU, and disk size.
  + If you use Amazon EC2 as the backend, make sure that the instance type has the appropriate resources to fulfill the incoming requests. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the *Amazon EC2 User Guide*.
+ **If you use API Gateway**:
  + This error is related to the backend integration when the API Gateway API is unable to receive a response. The backend server might be:
    + Overloaded beyond capacity and unable to process new client requests.
    + Under temporary maintenance.
  + To resolve this error, look at your API Gateway application logs to determine if there is an issue with backend capacity, integration, or something else.

## CloudFront caused the error due to resource constraints at the edge location
<a name="http-503-service-unavailable-limited-resources-at-edge-location"></a>

You will receive this error in the rare situation that CloudFront can't route requests to the next best available edge location, and so can't satisfy a request. This error is common when you perform load testing on your CloudFront distribution. To help prevent this, follow the [Load testing CloudFront](load-testing.md) guidelines for avoiding 503 (capacity exceeded) errors.

If this happens in your production environment, contact [Support](https://console.aws.amazon.com/support/home#/).

## Lambda@Edge or CloudFront Function execution error
<a name="http-503-lambda-execution-error"></a>

If you're using Lambda@Edge or CloudFront Functions, an HTTP 503 status code can indicate that your function returned an execution error. 

For more details about how to identify and resolve Lambda@Edge errors, see [Test and debug Lambda@Edge functions](lambda-edge-testing-debugging.md).

For more information about testing CloudFront Functions, see [Test functions](test-function.md).

## Lambda@Edge limit exceeded
<a name="http-503-lambda-limit-exceeded-error"></a>

If you're using Lambda@Edge, an HTTP 503 status code can indicate that Lambda returned an error. The error might be caused by one of the following:
+ The number of function executions exceeded one of the quotas that Lambda sets to throttle executions in an AWS Region (concurrent executions or invocation frequency).
+ The function exceeded the Lambda function timeout quota.

For more information about the Lambda@Edge quotas, see [Quotas on Lambda@Edge](cloudfront-limits.md#limits-lambda-at-edge). For more details about how to identify and resolve Lambda@Edge errors, see [Test and debug Lambda@Edge functions](lambda-edge-testing-debugging.md). You can also see the [Lambda service quotas](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html) in the *AWS Lambda Developer Guide*. 

# HTTP 504 status code (Gateway Timeout)
<a name="http-504-gateway-timeout"></a>

An HTTP 504 status code (gateway timeout) indicates that when CloudFront forwarded a request to the origin (because the requested object wasn't in the edge cache), one of the following happened:
+ The origin returned an HTTP 504 status code to CloudFront.
+ The origin didn't respond before the request expired.

CloudFront will return an HTTP 504 status code if traffic is blocked to the origin by a firewall or security group, or if the origin isn't accessible on the internet. Check for those issues first. Then, if access isn't the problem, explore application delays and server timeouts to help you identify and fix the issues.

**Topics**
+ [Configure the firewall on your origin server to allow CloudFront traffic](#http-504-gateway-timeout-configure-firewall)
+ [Configure the security groups on your origin server to allow CloudFront traffic](#http-504-gateway-timeout-configure-security-groups)
+ [Make your custom origin server accessible on the internet](#http-504-gateway-timeout-make-origin-accessible)
+ [Find and fix delayed responses from applications on your origin server](#http-504-gateway-timeout-slow-application)

## Configure the firewall on your origin server to allow CloudFront traffic
<a name="http-504-gateway-timeout-configure-firewall"></a>

If the firewall on your origin server blocks CloudFront traffic, CloudFront returns an HTTP 504 status code, so it's good to make sure that isn't the issue before checking for other problems.

The method that you use to determine if this is an issue with your firewall depends on what system your origin server uses:
+ If you use an IPTable firewall on a Linux server, you can search for tools and information to help you work with IPTables.
+ If you use Windows Firewall on a Windows server, see [Add or Edit Firewall Rule](https://technet.microsoft.com/en-us/library/cc753558(v=ws.11).aspx) in the Microsoft documentation.

When you evaluate the firewall configuration on your origin server, look for any firewalls or security rules that block traffic from CloudFront edge locations, based on the published IP address range. For more information, see [Locations and IP address ranges of CloudFront edge servers](LocationsOfEdgeServers.md).

If the CloudFront IP address range is allowed to connect to your origin server, make sure to update your server's security rules to incorporate changes. You can subscribe to an Amazon SNS topic and receive notifications when the IP address range file is updated. After you receive the notification, you can use code to retrieve the file, parse it, and make adjustments for your local environment. For more information, see [Subscribe to AWS Public IP Address Changes via Amazon SNS](https://aws.amazon.com/blogs/aws/subscribe-to-aws-public-ip-address-changes-via-amazon-sns/) on the AWS News Blog.

## Configure the security groups on your origin server to allow CloudFront traffic
<a name="http-504-gateway-timeout-configure-security-groups"></a>

If your origin uses Elastic Load Balancing, review the [ELB security groups](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-security-groups.html) and make sure that the security groups allow inbound traffic from CloudFront.

You can also use AWS Lambda to automatically update your security groups to allow inbound traffic from CloudFront.

## Make your custom origin server accessible on the internet
<a name="http-504-gateway-timeout-make-origin-accessible"></a>

If CloudFront can't access your custom origin server because it isn't publicly available on the internet, CloudFront returns an HTTP 504 error.

CloudFront edge locations connect to origin servers through the internet. If your custom origin is on a private network, CloudFront can't reach it. Because of this, you can't use private servers, including [internal Classic Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-internal-load-balancers.html), as origin servers with CloudFront.

To check that internet traffic can connect to your origin server, run the following commands (where *OriginDomainName* is the domain name for your server):

For HTTPS traffic:
+ nc -zv *OriginDomainName* 443
+ telnet *OriginDomainName* 443

For HTTP traffic:
+ nc -zv *OriginDomainName* 80
+ telnet *OriginDomainName* 80

## Find and fix delayed responses from applications on your origin server
<a name="http-504-gateway-timeout-slow-application"></a>

Server timeouts are often the result of either an application taking a very long time to respond, or a timeout value that is set too low.

A quick fix to help avoid HTTP 504 errors is to simply set a higher CloudFront timeout value for your distribution. But we recommend that you first make sure that you address any performance and latency issues with the application and origin server. Then you can set a reasonable timeout value that helps prevent HTTP 504 errors and provides good responsiveness to users.

Here's an overview of the steps you can take to find performance issues and correct them:

1. Measure the typical and high-load latency (responsiveness) of your web application.

1. Add additional resources, such as CPU or memory, if needed. Take other steps to address issues, such as tuning database queries to accommodate high-load scenarios.

1. If needed, adjust the timeout value for your CloudFront distribution.

Following are details about each step.

### Measure typical and high-load latency
<a name="http-504-gateway-timeout-slow-application-measure-latency"></a>

To determine if one or more backend web application servers are experiencing high latency, run the following Linux curl command on each server:

```
curl -w "DNS Lookup Time: %{time_namelookup} \nConnect time: %{time_connect} \nTLS Setup: %{time_appconnect} \nRedirect Time: %{time_redirect} \nTime to first byte: %{time_starttransfer} \nTotal time: %{time_total} \n" -o /dev/null https://www.example.com/yourobject
```

**Note**  
If you run Windows on your servers, you can search for and download curl for Windows to run a similar command.

As you measure and evaluate the latency of an application that runs on your server, keep in mind the following:
+ Latency values are relative to each application. However, a time to first byte in milliseconds rather than seconds or more, is reasonable.
+ If you measure the application latency under normal load and it's fine, be aware that viewers might still experience timeouts under high load. When there is high demand, servers can have delayed responses or not respond at all. To help prevent high-load latency issues, check your server's resources such as CPU, memory, and disk reads and writes to make sure that your servers have the capacity to scale for high load.

  You can run the following Linux command to check the memory that is used by Apache processes:

  `watch -n 1 "echo -n 'Apache Processes: ' && ps -C apache2 --no-headers | wc -l && free -m"`
+ High CPU utilization on the server can significantly reduce an application's performance. If you use an Amazon EC2 instance for your backend server, review the CloudWatch metrics for the server to check the CPU utilization. For more information, see the [Amazon CloudWatch User Guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html). Or if you're using your own server, refer to the server help documentation for instructions on how to check CPU utilization.
+ Check for other potential issues under high loads, such as database queries that run slowly when there's a high volume of requests.

### Add resources, and tune servers and databases
<a name="http-504-gateway-timeout-slow-application-add-resources"></a>

After you evaluate the responsiveness of your applications and servers, make sure that you have sufficient resources in place for typical traffic and high load situations:
+ If you have your own server, make sure it has enough CPU, memory, and disk space to handle viewer requests, based on your evaluation.
+ If you use an Amazon EC2 instance as your backend server, make sure that the instance type has the appropriate resources to fulfill incoming requests. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the *Amazon EC2 User Guide*.

In addition, consider the following tuning steps to help avoid timeouts:
+ If the Time to First Byte value that is returned by the curl command seems high, take steps to improve the performance of your application. Improving application responsiveness will in turn help reduce timeout errors.
+ Tune database queries to make sure that they can handle high request volumes without slow performance.
+ Set up [ keep-alive (persistent)](https://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01) connections on your backend server. This option helps to avoid latencies that occur when connections must be re-established for subsequent requests or users.
+ **If you use Elastic Load Balancing as your origin**, the following are possible causes for a 504 error:
  + The load balancer fails to establish a connection to the target before the connection timeout expires (10 seconds).
  + The load balancer establishes a connection to the target but the target doesn't respond before the idle timeout period elapses.
  + The network access control list (ACL) for the subnet doesn't allow traffic from the targets to the load balancer nodes on the ephemeral ports (1024-65535).
  + The target returns a content-length header that is larger than the entity body. The load balancer times out waiting for the missing bytes.
  + The target is a Lambda function and Lambda doesn't respond before the connection timeout expires.

  For more information about reducing latency, see [How do I troubleshoot high latency on my ELB Classic Load Balancer?](https://repost.aws/knowledge-center/elb-latency-troubleshooting)
+ **If you use MediaTailor as your origin**, the following are possible causes for a 504 error:
  + If relative URLs are mishandled, MediaTailor can receive malformed URLs from the players.
  + If MediaPackage is the manifest origin for MediaTailor, MediaPackage 404 manifest errors can cause MediaTailor to return a 504 error.
  + The request to the MediaTailor origin server takes more than 2 seconds to complete.
+ **If you use Amazon API Gateway as your origin**, the following is a possible cause for a 504 error:
  + An integration request takes longer than your API Gateway REST API maximum integration timeout parameter. For more information, see [How can I troubleshoot API HTTP 504 timeout errors with API Gateway?](https://repost.aws/knowledge-center/api-gateway-504-errors)

### If needed, adjust the CloudFront timeout value
<a name="http-504-gateway-timeout-slow-application-adjust-timeout"></a>

If you have evaluated and addressed slow application performance, origin server capacity, and other issues, but viewers are still experiencing HTTP 504 errors, then you should consider changing the time that is specified in your distribution for origin response timeout. For more information, see [Response timeout](DownloadDistValuesOrigin.md#DownloadDistValuesOriginResponseTimeout).