26

What is the algorithm used to generate etags in Nginx? They look something like "554b73dc-6f0d" now.

Are they generated from timestamp only?

2
  • 1
    I don't believe they contain an inode (unlike Apache by default)... although I'm having a hard time finding where I found that a long time ago (better for a cache cluster). Are you working in an environment without a useful clock (eg. embedded)? May 7, 2015 at 15:20
  • 1
    There is some related info in developer.yahoo.com/performance/rules.html#etags (but not regarding Nginx) May 7, 2015 at 15:26

2 Answers 2

44

From the source code: http://lxr.nginx.org/ident?_i=ngx_http_set_etag

1803 ngx_int_t
1804 ngx_http_set_etag(ngx_http_request_t *r)
1805 {
1806     ngx_table_elt_t           *etag;
1807     ngx_http_core_loc_conf_t  *clcf;
1808 
1809     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
1810 
1811     if (!clcf->etag) {
1812         return NGX_OK;
1813     }
1814 
1815     etag = ngx_list_push(&r->headers_out.headers);
1816     if (etag == NULL) {
1817         return NGX_ERROR;
1818     }
1819 
1820     etag->hash = 1;
1821     ngx_str_set(&etag->key, "ETag");
1822 
1823     etag->value.data = ngx_pnalloc(r->pool, NGX_OFF_T_LEN + NGX_TIME_T_LEN + 3);
1824     if (etag->value.data == NULL) {
1825         etag->hash = 0;
1826         return NGX_ERROR;
1827     }
1828 
1829     etag->value.len = ngx_sprintf(etag->value.data, "\"%xT-%xO\"",
1830                                   r->headers_out.last_modified_time,
1831                                   r->headers_out.content_length_n)
1832                       - etag->value.data;
1833 
1834     r->headers_out.etag = etag;
1835 
1836     return NGX_OK;
1837 }

You can see on lines 1830 and 1831 that the input is the last modified time and the content length.

2
2

In PHP who will need it.

$pathToFile = '/path/to/file.png';

$lastModified = filemtime($pathToFile);
$length = filesize($pathToFile);

header('ETag: "' . sprintf('%x-%x', $lastModified, $length) . '"');
11
  • 3
    How is this better than the accepted answer?
    – RalfFriedl
    Nov 24, 2018 at 14:21
  • 2
    @RalfFriedl this answer will be better for PHP programmers, because in the future some PHP programmer like me will look for 3 keywords "nginx", "etag", "alg" and he will find my answer. This perhaps will prevent the creation of duplication of questions.
    – Max_Payne
    Nov 24, 2018 at 14:34
  • 2
    @RalfFriedl it is easier to understand than the nginx source code for someone who is not that familiar with c. Aug 1, 2020 at 18:40
  • You really shouldn't be generating etags yourself. You should just store whatever value the server gives you.
    – Kevin Cox
    Aug 11, 2020 at 12:38
  • @KevinCox this is true for static files, but not for files generated dynamically (ex. using PHP).
    – Max_Payne
    Aug 12, 2020 at 12:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .