I set custom object caching on my CloudFront distribution. Why is my distribution using the cache settings of my origin?
Last updated: 2022-07-13
My Amazon CloudFront distribution has a cache behavior with object caching set to Customize, but my distribution still uses the cache settings of my origin. How can I fix this?
Short description
When you customize object caching, you configure the Default TTL, Minimum TTL, and Maximum TTL. CloudFront uses these parameters based on whether the origin returns a caching header:
- If the origin doesn’t return a caching header, then the distribution uses the Default TTL.
- If the origin returns a caching header that’s less than the Minimum TTL, then the distribution uses the Minimum TTL.
- If the origin returns a caching header that’s greater than the Maximum TTL, then the distribution uses the Maximum TTL.
Note: The response to the client contains the origin’s caching headers even when CloudFront caches the response based on Minimum TTL or Maximum TTL. The origin’s caching header can be used by any private cache, such as a browser or proxy.
If your CloudFront distribution isn’t caching based on the custom values that you set on cache behaviors, then check the origin. Verify whether the origin has any conflicting caching headers.
Resolution
To verify whether origin caching headers conflict with your distribution’s custom object caching, follow these instructions based on the issues you’re seeing:
The Minimum TTL and Default TTL are set to 0, but there are still hits from CloudFront
If there are hits from CloudFront even when a request URI matches a cache behavior path with Minimum TTL and Default TTL set to 0, then check the response from CloudFront. Verify whether the response shows the X-Cache header as «Hit from cloudfront» or «RefreshHit from cloudfront»:
< HTTP/1.1 200 OK
< Content-Type: text/html
< Content-Length: 437
< Connection: keep-alive
< Date: Sat, 03 Feb 2018 19:26:45 GMT
< Last-Modified: Sat, 03 Feb 2018 19:25:24 GMT
< ETag: "example12345abcdefghijklmno54321"
< Cache-Control: max-age=300, Public
< Accept-Ranges: bytes
< Server: AmazonS3
< Age: 14
< X-Cache: Hit from cloudfront
If the X-Cache header is «Hit from cloudfront» or «RefreshHit from cloudfront,» then the request was served from the cache of the edge location.
Review the rest of the response for the Cache-Control, Expires, and Age headers. The Cache-Control and Expires headers are behavioral caching headers that tell the intermediary (CloudFront) or private (browser) cache how to store a request. The Age header shows how long a response has been cached.
If the max-age value for Cache-Control is greater than the value for Age, then the cached response is considered new and is served from the edge location. If the Expires date is still in the future, then the cached response is also considered new. This occurs even if the cache behavior path has Minimum TTL and Default TTL set to 0.
The Maximum TTL and Default TTL are greater than 0, but there are misses from CloudFront
If there are misses from CloudFront even when a request URI matches a cache behavior path with Maximum TTL and Default TTL set to values greater than 0, check the response from CloudFront. Verify whether the response shows the X-Cache header as «Miss from cloudfront»:
< HTTP/1.1 200 OK
< Content-Type: text/html
< Content-Length: 437
< Connection: keep-alive
< Date: Sat, 03 Feb 2018 19:26:45 GMT
< Last-Modified: Sat, 03 Feb 2018 19:25:24 GMT
< ETag: "example12345abcdefghijklmno54321"
< Cache-Control: no-cache, no-store
< Accept-Ranges: bytes
< Server: AmazonS3
< X-Cache: Miss from cloudfront
If the X-Cache header is «Miss from cloudfront,» then the request was retrieved from the origin and wasn’t served by the cache.
Review the Cache-Control header in the response. If the value for Cache-Control is «no-store,» then the header is directing CloudFront to not cache the response. If the value for Cache-Control is «no-cache,» then the header is directing CloudFront to verify with the origin before returning a cached response. These directives supersede the Maximum TTL and Default TTL CloudFront settings.
Note: Responses that aren’t from the cache won’t have an Age header.
CloudFront is caching error responses
By default, CloudFront forwards error responses from the origin to the client. Additionally, CloudFront caches the origin’s error response for 10 seconds by default.
If the error response from the origin contains a Cache-Control header, CloudFront caches the error with the relevant TTL instead of the default 5 minutes. CloudFront doesn’t cache its own error responses, unless specified otherwise in a custom error response.
To determine whether the error response is from the origin or CloudFront, check the Server header. To determine whether the error is a cached response, check the Age header—a cached response includes an Age header.
The following example is an error from an Amazon Simple Storage Service (Amazon S3) origin that’s a cached response:
< HTTP/1.1 403 Forbidden
< Content-Type: application/xml
< Transfer-Encoding: chunked
< Connection: keep-alive
< Date: Sat, 03 Feb 2018 21:07:51 GMT
< Server: AmazonS3
< Age: 12
< X-Cache: Error from cloudfront
The following example is an error from CloudFront that isn’t a cached response:
< HTTP/1.1 403 Forbidden
< Server: CloudFront
< Date: Sat, 03 Feb 2018 21:14:53 GMT
< Content-Type: text/xml
< Content-Length: 146
< Connection: keep-alive
< X-Cache: Error from cloudfront
After you identify the conflicting caching headers, update the origin
After you determine which caching headers are superseding your distribution’s custom object caching, follow these steps:
- Identify where in the web server configuration the headers are applied.
- Remove the lines where the headers are applied.
- Restart the server.
- Test your origin directly to be sure that the caching headers are no longer returned in the response.
- Run an invalidation on your entire CloudFront distribution to apply the change.
Did this article help?
Do you need billing or technical support?
AWS support for Internet Explorer ends on 07/31/2022. Supported browsers are Chrome, Firefox, Edge, and Safari.
Learn more »
Amazon CloudFront can get tricky with its configuration and debugging an error code — to trace it back to its root cause can take several hours. However, you might want to make the following checks before you get into the logs.
Bucket Name!
The bucket names should match the names of the website that you are hosting.
For instance, to host your-domain.com website on Amazon S3, you would create a bucket named your-domain.com.
To host a website under www.your-domain.com, you would name the bucket www.your-domain.com.
Its a best practice, to create buckets for both your-domain.com and www.your-domain.com.
Use the existing logic in your settings/configuration for any one of these buckets and use it to serve the static website. Use the other bucket to redirect the request to the original bucket.
Honestly, this wouldn’t be causing you the trouble since you’ve integrated your system with Amazon CloudFront, which can be configured to use an Amazon S3 bucket of any name.
With Amazon CloudFront, users that visit your domain will directly fetch data from the CloudFront distribution which in turn caches contents from our S3 bucket.
Configuring the distribution’s Origin Settings.
While creating a distribution with Amazon CloudFront make note of the associated Amazon S3 endpoint with the Origin Domain Name. Make sure to use the web site endpoint and NOT the REST endpoint. Don’t use the endpoint auto-suggested by CloudFront.
There is a difference in the behavior as explained in the Amazon Web Services official documentation
4XX Error Code!
From your console logs, it suggests distribution instance is trying to access a forbidden element, page or resource and hence the 403 status code.
While the 404 is merely a result of page not found. However, after the error redirection — as handled in your configuration, the user is redirected back to index.html where it encounters the 403.
More information on — How CloudFront Processes and Caches HTTP 4xx and 5xx Status Codes from Your Origin
Other usual suspects include Caching Configurations for Amazon CloudFront distribution, AWS Route53 settings, and Amazon Certificate Manager.
As mentioned in the beginning it can get quite perplexing while tracking such errors. Let us know if the above helps. Also, I would really appreciate it if you could post updates on your investigations and findings.
Thanks for the read.
Содержание
- Как решить проблему «x-cache: Error from cloudfront» в SPA
- Самый простой способ удалить вредоносное ПО на устройстве Android [How-To]
- Название ведра!
- Настройка исходных настроек дистрибутива.
- 4XX Код ошибки!
- Среди других обычных подозреваемых — конфигурации кэширования для распространения Amazon CloudFront, настройки AWS Route53 и Amazon Certificate Manager.
- Why is my CloudFront distribution returning an “X-Cache:Miss from CloudFront” response?
- Resolution
- I set custom object caching on my CloudFront distribution. Why is my distribution using the cache settings of my origin?
- Short description
- Resolution
- Troubleshooting error “X-Cache: Miss from CloudFront”
- Dealing with error X-Cache: Miss from CloudFront
- Troubleshooting error X-Cache: Miss from CloudFront
- Conclusion
- PREVENT YOUR SERVER FROM CRASHING!
Как решить проблему «x-cache: Error from cloudfront» в SPA
Самый простой способ удалить вредоносное ПО на устройстве Android [How-To]
У нас возникают проблемы при попытке заставить работать SPA с клиентским маршрутизатором (реагирующим маршрутизатором). Мы используем концепцию «иметь DOMAIN -> CDN (CloudFront) -> S3 для обслуживания наших статических файлов.
Мы настроили S3 для обслуживания статических файлов. Сеть CDN настроена так, чтобы ее источник был S3, и мы настроили настраиваемые страницы ошибок для обнаружения ошибок:
с этой конфигурацией мы можем поймать такие ошибки:
CDN перенаправит все ошибки 404/403 на главную index.html а также react router получит правильную маршрутизацию.
У нас есть рабочий наш сайт, и клиентский маршрутизатор работает нормально, но у нас есть проблема с ответом нашего CDN с x-cache: Error from cloudfront :
Если мы получим доступ к основному URL https://www.example.com без какого-либо параметра запроса (не строки запроса) все работает нормально.
Как я могу решить эту проблему и заставить работать все мои динамические URL?
Когда вы посещаете http://mywebsite.com запрос попадет в index.html файл в S3. Затем вы можете нажать кнопку и перейти к http://mywebsite.com/stats который является внутренним маршрутом вашего приложения React. Таким образом, он не вызовет никаких внутренних запросов.
Но если вы перезагрузите страницу, http://mywebsite.com/stats будет отправлен на S3, поскольку ваш браузер не знает, что вы запускаете приложение React.
S3 вернет ошибку 403 с index.html, а Cloudfront отправит вам ошибку.
Решение использует краевую лямбда-функцию в облачной среде. Вот пример:
В Amazon CloudFront могут возникнуть сложности с настройкой и отладкой кода ошибки — на поиск первопричины может уйти несколько часов. Тем не менее, вы можете захотеть выполнить следующие проверки, прежде чем войти в журналы.
Название ведра!
Имена сегментов должны совпадать с именами веб-сайта, который вы размещаете.
Например, разместить your-domain.com веб-сайт на Amazon S3, вы должны создать корзину с именем your-domain.com.
Размещать сайт под www.your-domain.com, вы бы назвали ведро www.your-domain.com.
Лучше всего создавать корзины как для your-domain.com, так и для www.your-domain.com.
Используйте существующую логику в ваших настройках / конфигурации для любого из этих сегментов и используйте ее для обслуживания статического веб-сайта. Используйте другой сегмент, чтобы перенаправить запрос в исходный сегмент.
Честно говоря, это не доставит вам проблем, поскольку вы интегрировали свою систему с Amazon CloudFront, который можно настроить для использования корзины Amazon S3 с любым именем.
С помощью Amazon CloudFront пользователи, посещающие ваш домен, будут напрямую получать данные из дистрибутива CloudFront, который, в свою очередь, кэширует содержимое из нашей корзины S3.
Настройка исходных настроек дистрибутива.
При создании распространения с помощью Amazon CloudFront обратите внимание на связанную конечную точку Amazon S3 с доменным именем источника. Обязательно используйте конечную точку веб-сайта и НЕ конечная точка REST. Не используйте конечную точку, автоматически предложенную CloudFront.
Существует разница в поведении, как описано в официальной документации Amazon Web Services.
4XX Код ошибки!
Из журналов вашей консоли он предполагает, что экземпляр распространения пытается получить доступ к запрещенному элементу, странице или ресурсу и, следовательно, к коду состояния 403.
В то время как 404 — это просто результат того, что страница не найдена. Однако после перенаправления ошибки, как описано в вашей конфигурации, пользователь перенаправляется обратно в index.html где он встречает 403.
Дополнительная информация о том, как CloudFront обрабатывает и кэширует коды состояния HTTP 4xx и 5xx из вашего источника
Среди других обычных подозреваемых — конфигурации кэширования для распространения Amazon CloudFront, настройки AWS Route53 и Amazon Certificate Manager.
Как упоминалось в начале, отслеживание таких ошибок может вызвать затруднения. Сообщите нам, поможет ли это. Кроме того, я был бы очень признателен, если бы вы могли публиковать новости о своих исследованиях и выводах.
Источник
Why is my CloudFront distribution returning an “X-Cache:Miss from CloudFront” response?
Last updated: 2022-01-29
I configured my Amazon CloudFront distribution and origin to cache objects, but my distribution is returning an «X-Cache:Miss from CloudFront» response. Why is this happening? What can I do to avoid this response?
Resolution
To diagnose and troubleshoot a «X-Cache:Miss from CloudFront» response, check the following:
Which edge location is receiving the requests?
After an object is requested through CloudFront, the object is cached only in the edge location that received the request. If a subsequent request is made to another edge location, the other edge location won’t have a cached version of the object. This scenario returns an «X-Cache:Miss from CloudFront» response.
To determine if the response is coming from one edge location or from multiple edge locations, send several requests from the same client to the same object. Then, check the IP addresses that the connection is established on. Run a reverse DNS lookup on the IP addresses to determine which edge location the requests are going to.
You can also determine the edge location by checking the value of the «x-amz-cf-pop» response header after making a request to your CloudFront distribution.
How frequently is the object requested?
If an object in an edge location isn’t requested frequently, then CloudFront might remove the object before its expiration date. For more information on when CloudFront evicts objects, see Managing how long content stays in the cache (expiration).
If you’re seeing the «X-Cache:Miss from CloudFront» response intermittently, then CloudFront might be removing the object because of infrequent requests.
Is the CloudFront distribution configured to forward any headers, cookies, or query string parameters?
If your distribution is configured to forward headers, cookies, or query string parameters, then the distribution caches requests based on those parameters. The parameters reduce the number of requests served from the cache.
For example, if two requests to access an object have different values in query string parameters, then the second request isn’t served from the cache. The second request returns the «X-Cache:Miss from CloudFront» response.
To determine if forwarding headers, cookies, or query string parameters are causing the response, configure the CloudFront distribution to not forward these parameters to the origin. Then, check to see if the issue persists.
If the issue resolves after the distribution no longer forwards those parameters, then at least one parameter is causing the response. Rather than configuring CloudFront to forward a wide range of parameter, add to the allow list only the specific parameters you want CloudFront to forward.
Is the response stored in the browser cache?
After a request returns the «X-Cache:Miss from CloudFront» response, the browser might serve the same response to subsequent requests because it’s stored in the browser cache.
To verify if the response is stored in the browser cache, clear the browser cache and make a new request for the same object.
Note: To determine how long the browser caches the object, check to see if any Cache-Control or Expires headers are set on the object.
Источник
I set custom object caching on my CloudFront distribution. Why is my distribution using the cache settings of my origin?
Last updated: 2022-07-13
Short description
When you customize object caching, you configure the Default TTL, Minimum TTL, and Maximum TTL. CloudFront uses these parameters based on whether the origin returns a caching header:
- If the origin doesn’t return a caching header, then the distribution uses the Default TTL.
- If the origin returns a caching header that’s less than the Minimum TTL, then the distribution uses the Minimum TTL.
- If the origin returns a caching header that’s greater than the Maximum TTL, then the distribution uses the Maximum TTL.
Note: The response to the client contains the origin’s caching headers even when CloudFront caches the response based on Minimum TTL or Maximum TTL. The origin’s caching header can be used by any private cache, such as a browser or proxy.
If your CloudFront distribution isn’t caching based on the custom values that you set on cache behaviors, then check the origin. Verify whether the origin has any conflicting caching headers.
Resolution
To verify whether origin caching headers conflict with your distribution’s custom object caching, follow these instructions based on the issues you’re seeing:
The Minimum TTL and Default TTL are set to 0, but there are still hits from CloudFront
If there are hits from CloudFront even when a request URI matches a cache behavior path with Minimum TTL and Default TTL set to 0, then check the response from CloudFront. Verify whether the response shows the X-Cache header as «Hit from cloudfront» or «RefreshHit from cloudfront»:
If the X-Cache header is «Hit from cloudfront» or «RefreshHit from cloudfront,» then the request was served from the cache of the edge location.
Review the rest of the response for the Cache-Control, Expires, and Age headers. The Cache-Control and Expires headers are behavioral caching headers that tell the intermediary (CloudFront) or private (browser) cache how to store a request. The Age header shows how long a response has been cached.
If the max-age value for Cache-Control is greater than the value for Age, then the cached response is considered new and is served from the edge location. If the Expires date is still in the future, then the cached response is also considered new. This occurs even if the cache behavior path has Minimum TTL and Default TTL set to 0.
The Maximum TTL and Default TTL are greater than 0, but there are misses from CloudFront
If there are misses from CloudFront even when a request URI matches a cache behavior path with Maximum TTL and Default TTL set to values greater than 0, check the response from CloudFront. Verify whether the response shows the X-Cache header as «Miss from cloudfront»:
If the X-Cache header is «Miss from cloudfront,» then the request was retrieved from the origin and wasn’t served by the cache.
Review the Cache-Control header in the response. If the value for Cache-Control is «no-store,» then the header is directing CloudFront to not cache the response. If the value for Cache-Control is «no-cache,» then the header is directing CloudFront to verify with the origin before returning a cached response. These directives supersede the Maximum TTL and Default TTL CloudFront settings.
Note: Responses that aren’t from the cache won’t have an Age header.
CloudFront is caching error responses
By default, CloudFront forwards error responses from the origin to the client. Additionally, CloudFront caches the origin’s error response for 10 seconds by default.
If the error response from the origin contains a Cache-Control header, CloudFront caches the error with the relevant TTL instead of the default 5 minutes. CloudFront doesn’t cache its own error responses, unless specified otherwise in a custom error response.
To determine whether the error response is from the origin or CloudFront, check the Server header. To determine whether the error is a cached response, check the Age header—a cached response includes an Age header.
The following example is an error from an Amazon Simple Storage Service (Amazon S3) origin that’s a cached response:
The following example is an error from CloudFront that isn’t a cached response:
After you identify the conflicting caching headers, update the origin
After you determine which caching headers are superseding your distribution’s custom object caching, follow these steps:
- Identify where in the web server configuration the headers are applied.
- Remove the lines where the headers are applied.
- Restart the server.
- Test your origin directly to be sure that the caching headers are no longer returned in the response.
- Run an invalidation on your entire CloudFront distribution to apply the change.
Источник
Troubleshooting error “X-Cache: Miss from CloudFront”
by Nikhath K | Oct 2, 2021
Stuck with error X-Cache: Miss from CloudFront? Find out what our expert Support Engineers suggest.
At Bobcares, we help our customers with errors like “X-cache: Miss from CloudFront” and plenty more. Let’s dive in and find out how our Support Team resolved this particular error today.
Dealing with error X-Cache: Miss from CloudFront
If your CloudFront distribution is returning an “X-Cache: Miss from CloudFront”, you have come to the right place.
Once the object is requested through CloudFront, it is cached in the edge location that got the request. In case another request is made to a different edge location, it will not have the cached version of the requested object. Ultimately, this results in the X-Cache: Miss from CloudFront error.
Troubleshooting error X-Cache: Miss from CloudFront
Which edge location received the request?
One way of resolving the error is by checking whether the errors response is from an edge location or multiple edge locations. This can be done by sending multiple requests to the same object from the same client. Once this is done, check the IP addresses and run a reverse DNS lookup to find out which edge location received the requests.
Frequency of object requests
If the object in an edge location is not requested frequently, it gets removed by CloudFront before its expiration date. If you come across the error message intermittently, this might be the cause of the error.
Forwarding cookies, headers, or query string parameter
When the CloudFront distribution forwards cookies, headers, or query string parameters, the requests get cached. Moreover, this brings down the number of requests served.
For instance, if two requests for the same object have different query string parameter values the second request will not be served, resulting in the X-Cache: Miss from CloudFront error message.
First, determine whether this is the reason behind the error by configuring CloudFront distribution to stop forwarding these parameters. If the error still persists, take a look at the other reasons mentioned by our Support Engineers.
In case the error stops after removing the parameters, you can white list certain specific parameters rather than the entire range to prevent the error.
Response store in the browser cache
Once a particular request results in the X-Cache: Miss from CloudFront message, the browser may serve the same response to other requests since it is stored in the browser cache. Our Support Teams recommend clearing the cache and making a new request once more to avoid the error message.
[ Looking for help? We are at your service.]
Conclusion
In the end, we looked at different ways to troubleshoot the Miss from CloudFront error message. With Bobcares by your side, you need not look further for AWS Support Service.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
Источник
When you visit http://mywebsite.com the request will hit the index.html file in S3. Then you might click a button and go to http://mywebsite.com/stats which is an internal route of your SPA app. Thus, it will not trigger any backend request.
But if you reload the page, http://mywebsite.com/stats will be sent to S3 as your browser does not know that you are running an SPA frontend.
S3 will return 403 error with index.html and Cloudfront will send you the error.
Solution is using an edge lambda function in Cloudfront. Here an example:
const path = require('path')
exports.handler = (evt, ctx, cb) => {
const {request} = evt.Records[0].cf
if (!path.extname(request.uri)) {
request.uri = '/index.html'
}
cb(null, request)
}
Source: https://hackernoon.com/how-to-host-a-single-page-application-with-aws-cloudfront-and-lambda-edge-39ce7b036da2
Amazon CloudFront can get tricky with its configuration and debugging an error code — to trace it back to its root cause can take several hours. However, you might want to make the following checks before you get into the logs.
Bucket Name!
The bucket names should match the names of the website that you are hosting.
For instance, to host your-domain.com website on Amazon S3, you would create a bucket named your-domain.com.
To host a website under www.your-domain.com, you would name the bucket www.your-domain.com.
Its a best practice, to create buckets for both your-domain.com and www.your-domain.com.
Use the existing logic in your settings/configuration for any one of these buckets and use it to serve the static website. Use the other bucket to redirect the request to the original bucket.
Honestly, this wouldn’t be causing you the trouble since you’ve integrated your system with Amazon CloudFront, which can be configured to use an Amazon S3 bucket of any name.
With Amazon CloudFront, users that visit your domain will directly fetch data from the CloudFront distribution which in turn caches contents from our S3 bucket.
Configuring the distribution’s Origin Settings.
While creating a distribution with Amazon CloudFront make note of the associated Amazon S3 endpoint with the Origin Domain Name. Make sure to use the web site endpoint and NOT the REST endpoint. Don’t use the endpoint auto-suggested by CloudFront.
There is a difference in the behavior as explained in the Amazon Web Services official documentation
4XX Error Code!
From your console logs, it suggests distribution instance is trying to access a forbidden element, page or resource and hence the 403 status code.
While the 404 is merely a result of page not found. However, after the error redirection — as handled in your configuration, the user is redirected back to index.html where it encounters the 403.
More information on — How CloudFront Processes and Caches HTTP 4xx and 5xx Status Codes from Your Origin
Other usual suspects include Caching Configurations for Amazon CloudFront distribution, AWS Route53 settings, and Amazon Certificate Manager.
As mentioned in the beginning it can get quite perplexing while tracking such errors. Let us know if the above helps. Also, I would really appreciate it if you could post updates on your investigations and findings.
Thanks for the read.
Stuck with error X-Cache: Miss from CloudFront? Find out what our expert Support Engineers suggest.
At Bobcares, we help our customers with errors like “X-cache: Miss from CloudFront” and plenty more. Let’s dive in and find out how our Support Team resolved this particular error today.
Dealing with error X-Cache: Miss from CloudFront
If your CloudFront distribution is returning an “X-Cache: Miss from CloudFront”, you have come to the right place.
Once the object is requested through CloudFront, it is cached in the edge location that got the request. In case another request is made to a different edge location, it will not have the cached version of the requested object. Ultimately, this results in the X-Cache: Miss from CloudFront error.
Troubleshooting error X-Cache: Miss from CloudFront
Which edge location received the request?
One way of resolving the error is by checking whether the errors response is from an edge location or multiple edge locations. This can be done by sending multiple requests to the same object from the same client. Once this is done, check the IP addresses and run a reverse DNS lookup to find out which edge location received the requests.
Frequency of object requests
If the object in an edge location is not requested frequently, it gets removed by CloudFront before its expiration date. If you come across the error message intermittently, this might be the cause of the error.
Forwarding cookies, headers, or query string parameter
When the CloudFront distribution forwards cookies, headers, or query string parameters, the requests get cached. Moreover, this brings down the number of requests served.
For instance, if two requests for the same object have different query string parameter values the second request will not be served, resulting in the X-Cache: Miss from CloudFront error message.
First, determine whether this is the reason behind the error by configuring CloudFront distribution to stop forwarding these parameters. If the error still persists, take a look at the other reasons mentioned by our Support Engineers.
In case the error stops after removing the parameters, you can white list certain specific parameters rather than the entire range to prevent the error.
Response store in the browser cache
Once a particular request results in the X-Cache: Miss from CloudFront message, the browser may serve the same response to other requests since it is stored in the browser cache. Our Support Teams recommend clearing the cache and making a new request once more to avoid the error message.
[ Looking for help? We are at your service.]
Conclusion
In the end, we looked at different ways to troubleshoot the Miss from CloudFront error message. With Bobcares by your side, you need not look further for AWS Support Service.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
Самый простой способ удалить вредоносное ПО на устройстве Android [How-To]
У нас возникают проблемы при попытке заставить работать SPA с клиентским маршрутизатором (реагирующим маршрутизатором). Мы используем концепцию «иметь DOMAIN -> CDN (CloudFront) -> S3 для обслуживания наших статических файлов.
Мы настроили S3 для обслуживания статических файлов. Сеть CDN настроена так, чтобы ее источник был S3, и мы настроили настраиваемые страницы ошибок для обнаружения ошибок:
с этой конфигурацией мы можем поймать такие ошибки:
https://www.example.com/custom-url
CDN перенаправит все ошибки 404/403 на главную index.html а также react router получит правильную маршрутизацию.
У нас есть рабочий наш сайт, и клиентский маршрутизатор работает нормально, но у нас есть проблема с ответом нашего CDN с x-cache: Error from cloudfront:
Если мы получим доступ к основному URL https://www.example.com без какого-либо параметра запроса (не строки запроса) все работает нормально.
Как я могу решить эту проблему и заставить работать все мои динамические URL?
Спасибо.
Когда вы посещаете http://mywebsite.com запрос попадет в index.html файл в S3. Затем вы можете нажать кнопку и перейти к http://mywebsite.com/stats который является внутренним маршрутом вашего приложения React. Таким образом, он не вызовет никаких внутренних запросов.
Но если вы перезагрузите страницу, http://mywebsite.com/stats будет отправлен на S3, поскольку ваш браузер не знает, что вы запускаете приложение React.
S3 вернет ошибку 403 с index.html, а Cloudfront отправит вам ошибку.
Решение использует краевую лямбда-функцию в облачной среде. Вот пример:
const path = require('path') exports.handler = (evt, ctx, cb) => { const {request} = evt.Records[0].cf if (!path.extname(request.uri)) { request.uri = '/index.html' } cb(null, request) }
Источник: https://hackernoon.com/how-to-host-a-single-page-application-with-aws-cloudfront-and-lambda-edge-39ce7b036da2
В Amazon CloudFront могут возникнуть сложности с настройкой и отладкой кода ошибки — на поиск первопричины может уйти несколько часов. Тем не менее, вы можете захотеть выполнить следующие проверки, прежде чем войти в журналы.
Название ведра!
Имена сегментов должны совпадать с именами веб-сайта, который вы размещаете.
Например, разместить your-domain.com веб-сайт на Amazon S3, вы должны создать корзину с именем your-domain.com.
Размещать сайт под www.your-domain.com, вы бы назвали ведро www.your-domain.com.
Лучше всего создавать корзины как для your-domain.com, так и для www.your-domain.com.
Используйте существующую логику в ваших настройках / конфигурации для любого из этих сегментов и используйте ее для обслуживания статического веб-сайта. Используйте другой сегмент, чтобы перенаправить запрос в исходный сегмент.
Честно говоря, это не доставит вам проблем, поскольку вы интегрировали свою систему с Amazon CloudFront, который можно настроить для использования корзины Amazon S3 с любым именем.
С помощью Amazon CloudFront пользователи, посещающие ваш домен, будут напрямую получать данные из дистрибутива CloudFront, который, в свою очередь, кэширует содержимое из нашей корзины S3.
Настройка исходных настроек дистрибутива.
При создании распространения с помощью Amazon CloudFront обратите внимание на связанную конечную точку Amazon S3 с доменным именем источника. Обязательно используйте конечную точку веб-сайта и НЕ конечная точка REST. Не используйте конечную точку, автоматически предложенную CloudFront.
Существует разница в поведении, как описано в официальной документации Amazon Web Services.
4XX Код ошибки!
Из журналов вашей консоли он предполагает, что экземпляр распространения пытается получить доступ к запрещенному элементу, странице или ресурсу и, следовательно, к коду состояния 403.
В то время как 404 — это просто результат того, что страница не найдена. Однако после перенаправления ошибки, как описано в вашей конфигурации, пользователь перенаправляется обратно в index.html где он встречает 403.
Дополнительная информация о том, как CloudFront обрабатывает и кэширует коды состояния HTTP 4xx и 5xx из вашего источника
Среди других обычных подозреваемых — конфигурации кэширования для распространения Amazon CloudFront, настройки AWS Route53 и Amazon Certificate Manager.
Как упоминалось в начале, отслеживание таких ошибок может вызвать затруднения. Сообщите нам, поможет ли это. Кроме того, я был бы очень признателен, если бы вы могли публиковать новости о своих исследованиях и выводах.
Спасибо за прочитанное.
Tweet
Share
Link
Plus
Send
Send
Pin
Feeds
HomePopular
Topics
ValheimGenshin ImpactMinecraftPokimaneHalo InfiniteCall of Duty: WarzonePath of ExileHollow Knight: SilksongEscape from TarkovWatch Dogs: Legion
NFLNBAMegan AndersonAtlanta HawksLos Angeles LakersBoston CelticsArsenal F.C.Philadelphia 76ersPremier LeagueUFC
GameStopModernaPfizerJohnson & JohnsonAstraZenecaWalgreensBest BuyNovavaxSpaceXTesla
CardanoDogecoinAlgorandBitcoinLitecoinBasic Attention TokenBitcoin Cash
The Real Housewives of AtlantaThe BachelorSister Wives90 Day FianceWife SwapThe Amazing Race AustraliaMarried at First SightThe Real Housewives of DallasMy 600-lb LifeLast Week Tonight with John Oliver
Kim KardashianDoja CatIggy AzaleaAnya Taylor-JoyJamie Lee CurtisNatalie PortmanHenry CavillMillie Bobby BrownTom HiddlestonKeanu Reeves
Animals and PetsAnimeArtCars and Motor VehiclesCrafts and DIYCulture, Race, and EthnicityEthics and PhilosophyFashionFood and DrinkHistoryHobbiesLawLearning and EducationMilitaryMoviesMusicPlacePodcasts and StreamersPoliticsProgrammingReading, Writing, and LiteratureReligion and SpiritualityScienceTabletop GamesTechnologyTravel
Create an account to follow your favorite communities and start taking part in conversations.
Posts
Binance Ecosystem
Social
Downloads
r/binance
5
Posted by2 years ago
General
Note for future self: if binance webpage does not work and you get error 403 for all scripts and media «x-cache: Error from cloudfront» (example: https://s1.gifyu.com/images/binance.png ) then disable referer spoofing and http/2.
mods plz do not delete as it may help somebody else (e.g. https://old.reddit.com/r/BinanceExchange/comments/99i1eb/firefox_6102/ )
2 comments
68% Upvoted
level 1
· 2 yr. ago
Thanks! Couldn’t figure out what was going on here for a long time.
1
About Community
r/binance
Binance is the world’s leading blockchain and cryptocurrency infrastructure provider with a financial product suite that includes the largest digital asset exchange by volume.
Created Jul 1, 2017
888k
Binancians
2.2k
Online
Top 1%
Ranked by Size
Top posts september 20th 2020Top posts of september, 2020Top posts 2020
User AgreementPrivacy policy
Content policyModerator Code of Conduct
Reddit Inc © 2023. All rights reserved





