ETag Header Does Not Return 304

I am currently working on a REST API. I wanted to check if the HTTP cache works, but unfortunately I don't work at all. No matter what I do, it always returns HTTP code 200, while it should return 304 from what I know.

Here is my PHP code:

public function getList() { $this->addHeaders(array( 'Cache-Control' => 'public, must-revalidate, max-age=120', 'eTag' => 'xyz123', )); $array = array( 'foo' => 'bar', 'nested' => array( 'lorem' => 'ipsum', 'dolor' => 'sit amet' ) ); $this->addHeader('Content-Length', strlen(json_encode($array, true))); return new JsonModel($array); } 

response / request

enter image description here

The ETag does not change, so requests, with the exception of the first, must be sent from the cache. I'm wrong?

I followed these two articles:

I also checked with a weak validator - Last-Modified, but I have the same problem. The browser sends the correct header to the Request , but I still get 200 in response

+5
source share
3 answers

ETag requires the server to send a 304 response back to start a cache download.

In a time-based cache:

  • The client performs the initial request, caches the response for a specific time
  • In subsequent requests, if the resource is in the cache, it is used without accessing the server for this resource

In ETag-based cache:

  • The client executes the initial request, caches the response for a certain time along with the ETag from the server for this resource
  • In subsequent requests, if the resource is in the cache, the ETag is included in the new server request as an If-None-Match field.
  • The server checks the If-None-Match header and, if it matches the contents on the server, sends 304, not changed, which instructs the client’s cache to use its local copy. If the ETag is different, then the server returns the resource as usual.

To make your code work, you need to check for the If-None-Match header in PHP:

 If(isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == 'xyz123') { header("HTTP/1.1 304 Not Modified"); exit(); } 
+5
source

Your client sends a Cache-Control header with a value of max-age=0 . This tells the server that the client is requesting a new response, and the server sends an HTTP 200 status code.

The Cache-Control header sent by the client is usually the result of using developer tools in the browser and does not disable the Disable Caching option.

+1
source

It looks like you have not implemented any logic to check eTag headers. This cannot happen automatically because the server does not understand the business logic and therefore cannot determine when it is time to invalidate the cache.

There is another answer that describes the minimum setup .

0
source

Source: https://habr.com/ru/post/1259468/


All Articles