Does the ETag header make the Cache-Control header obsolete? How to make sure Cache-Control is not harmful then?

六眼飞鱼酱① 提交于 2019-12-13 04:36:32

问题


Definition of ETag header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag):

The ETag HTTP response header is an identifier for a specific version of a resource. It allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed. On the other side, if the content has changed, etags are useful to help prevent simultaneous updates of a resource from overwriting each other ("mid-air collisions").

Definition of Cache-Control header (https://developer.mozilla.org/de/docs/Web/HTTP/Headers/Cache-Control):

The Cache-Control general-header field is used to specify directives for caching mechanisms in both requests and responses.

So the ETag header tells the browser for a resource to send a single HTTP request to the server and ask if the file hash has changed. If yes, download a new one. Great. So if the ETag header is set why should I need Cache-Control any more (beside of the Expires header which may help to avoid this single request)?

So if I have to set the Cache-Control header anyway it can only be harmful right? I think the most appropriate value would be:

Cache-Control: must-revalidate

But I am not sure if this triggers unecessary additional actions.


回答1:


After some research, I found a great tutorial on Medium by Alex Barashkov: "Best practices for cache control settings for your website".

Alex writes:

I recommend you apply Cache-Control: no-cache to html files. Applying “no-cache” does not mean that there is no cache at all, it simply tells the browser to validate resources on the server before use it from the cache. That’s why we need to use it with Etag, so browsers will send a simple request and load the extra 80 bytes to verify the state of the file.




回答2:


Presence of ETag header does not tell the browser to do anything. Browser decides what to do based on the Cache-Control header it receives in the request and cached response. If it decides that resource is stale or needs to be re-validated, then it can use the ETag value to create a conditional request to the server and either get a new resource (status code 200), or a notification that things have not changed (status code 304)

Both headers are necessary for your cache to work optimally.



来源:https://stackoverflow.com/questions/55025948/does-the-etag-header-make-the-cache-control-header-obsolete-how-to-make-sure-ca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!