Several conditions need to be met for eTAG generation
- When the file doesn’t change,
etag
The value stays the same. So you can’t just use itinode
- Easy to calculate, not special CPU consumption. It looks like
hash
Not particularly suitable - Easy horizontal expansion, multiple
node
Generated on theetag
Value is consistent. It looks likeinode
Rules out
For details on how to generate etags in servers, see HTTP: Generating etag Header
So how is eTag generated in Nginx?
ETag generation in nginx
I found some materials and source code on the Internet to understand the calculation method of ETAG. The calculation is shown in Python pseudocode as follows
etag = '{:x}-{:x}'.format(header.last_modified, header.content_lenth)Copy the code
Source: ngx_http_core_modules. C
etag->value.len = ngx_sprintf(etag->value.data, "\"%xT-%xO\"",
r->headers_out.last_modified_time,
r->headers_out.content_length_n)
- etag->value.data;Copy the code
Summary: The etag in nginx is a hexadecimal combination of last-Modified and Content-Length representations of the response header.
Find an Nginx service in my K8S cluster and test it
$curl --head 10.97.109.49 HTTP/1.1 200 OK Server: nginx/1.16.0 Date: Tue, 10 Dec 2019 06:45:24 GMT Content-Type: text/html Content-Length: 612 Last-Modified: Tue, 23 Apr 2019 10:18:21 GMT Connection: keep-alive ETag: "5cbee66d-264" Accept-Ranges: bytesCopy the code
Last-modified and Content-Length are calculated by eTAG and js as follows, and the results are consistent
> new Date(parseInt('5cbee66d', 16) * 1000). ToJSON () "2019-04-23t10:18:21.000z" > parseInt('264', 16Copy the code
Last-modified, ETag and negotiated cache
We know that there are two ways to negotiate a cache
Last-Modified
/if-Modified-Since
ETag
/If-None-Match
Since ETag in Nginx is made up of last-Modified and content-Length, it is a last-modified version. Where is the last-modified version?
Last-modified is represented by a Unix timestamp, which means it can only work on second-level changes
Next question: If the ETag value in the HTTP response header changes, does that mean that the file content must have changed
I am Shanyue94, you can add my wechat shanyue94 to communicate with me