In short
Expires
header instructs the browser how long it should cache content in client side cache. Browser will serve the content from client side cache until the expiration date is reached.
When client side cache is expired browser will send request to server again. Request includes If-None-Match
header with the previous Etag
value it received from server. If value of If-None-Match
header still matches current Etag
value on server it will respond with 304 Not Modified
.
When you use Etag
and If-None-Match
headers and want server to send updated content, value of Etag
header must change.
Longer explanation
Lest assume you have the following code.
$app = new \Slim\Slim();
$app->get("/hello", function() use ($app){
$app->etag("unique-etag-1");
echo "Hello world.
";
});
$app->run();
Then you make a request.
$ curl --include http://localhost:8080/hello
HTTP/1.1 200 OK
Host: localhost:8080
Connection: close
X-Powered-By: PHP/5.6.2
Content-type: text/html;charset=UTF-8
Etag: "unique-etag-1"
Hello world
On subsequent requests browser will send If-None-Match
request header. Value of this header is the same as value of previously received Etag
header.
When Slim receives the request it compares the value of If-None-Match
header to the value you set with $app->etag()
call. If these match 304 Not Modified
will be returned.
$ curl --include --header 'If-None-Match: "unique-etag-1"' http://localhost:8080/hello
HTTP/1.1 304 Not Modified
Host: localhost:8080
Connection: close
X-Powered-By: PHP/5.6.2
Etag: "unique-etag-1"
Content-type: text/html; charset=UTF-8
If the content of URI changes or you want to browser to refetch the content for some other reasons, change the value of Etag
header.
$app->get("/hello", function() use ($app){
$app->etag("unique-etag-2");
echo "Hello world.
";
});
Now when browser makes new request you will get 200 OK
response.
curl --include --header 'If-None-Match: "unique-etag-1"' http://localhost:8080/hello
HTTP/1.1 200 OK
Host: localhost:8080
Connection: close
X-Powered-By: PHP/5.6.2
Content-type: text/html;charset=UTF-8
Etag: "unique-etag-2"
Hello world.