• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

src/H22-Jan-2020-4,0132,794

t/H22-Jan-2020-10,3588,132

util/H22-Jan-2020-7655

.gitattributesH A D22-Jan-202027 21

.gitignoreH A D22-Jan-2020815 8079

.travis.ymlH A D22-Jan-20204 KiB8877

ChangesH A D22-Jan-20201.1 KiB1714

README.markdownH A D22-Jan-202046.1 KiB1,154758

configH A D22-Jan-20202.3 KiB5144

valgrind.suppressH A D22-Jan-20201.7 KiB9493

README.markdown

1Name
2====
3
4**ngx_srcache** - Transparent subrequest-based caching layout for arbitrary nginx locations
5
6*This module is not distributed with the Nginx source.* See [the installation instructions](#installation).
7
8Table of Contents
9=================
10
11* [Name](#name)
12* [Status](#status)
13* [Version](#version)
14* [Synopsis](#synopsis)
15* [Description](#description)
16    * [Subrequest caching](#subrequest-caching)
17    * [Distributed Memcached Caching](#distributed-memcached-caching)
18    * [Caching with Redis](#caching-with-redis)
19    * [Cache Key Preprocessing](#cache-key-preprocessing)
20* [Directives](#directives)
21    * [srcache_fetch](#srcache_fetch)
22    * [srcache_fetch_skip](#srcache_fetch_skip)
23    * [srcache_store](#srcache_store)
24    * [srcache_store_max_size](#srcache_store_max_size)
25    * [srcache_store_skip](#srcache_store_skip)
26    * [srcache_store_statuses](#srcache_store_statuses)
27    * [srcache_store_ranges](#srcache_store_ranges)
28    * [srcache_header_buffer_size](#srcache_header_buffer_size)
29    * [srcache_store_hide_header](#srcache_store_hide_header)
30    * [srcache_store_pass_header](#srcache_store_pass_header)
31    * [srcache_methods](#srcache_methods)
32    * [srcache_ignore_content_encoding](#srcache_ignore_content_encoding)
33    * [srcache_request_cache_control](#srcache_request_cache_control)
34    * [srcache_response_cache_control](#srcache_response_cache_control)
35    * [srcache_store_no_store](#srcache_store_no_store)
36    * [srcache_store_no_cache](#srcache_store_no_cache)
37    * [srcache_store_private](#srcache_store_private)
38    * [srcache_default_expire](#srcache_default_expire)
39    * [srcache_max_expire](#srcache_max_expire)
40* [Variables](#variables)
41    * [$srcache_expire](#srcache_expire)
42    * [$srcache_fetch_status](#srcache_fetch_status)
43    * [$srcache_store_status](#srcache_store_status)
44* [Known Issues](#known-issues)
45* [Caveats](#caveats)
46* [Trouble Shooting](#trouble-shooting)
47* [Installation](#installation)
48* [Compatibility](#compatibility)
49* [Community](#community)
50    * [English Mailing List](#english-mailing-list)
51    * [Chinese Mailing List](#chinese-mailing-list)
52* [Bugs and Patches](#bugs-and-patches)
53* [Source Repository](#source-repository)
54* [Test Suite](#test-suite)
55* [TODO](#todo)
56* [Getting involved](#getting-involved)
57* [Author](#author)
58* [Copyright & License](#copyright--license)
59* [See Also](#see-also)
60
61Status
62======
63
64This module is production ready.
65
66Version
67=======
68
69This document describes srcache-nginx-module [v0.31](https://github.com/openresty/srcache-nginx-module/tags) released on 15 May 2016.
70
71Synopsis
72========
73
74```nginx
75
76 upstream my_memcached {
77     server 10.62.136.7:11211;
78     keepalive 10;
79 }
80
81 location = /memc {
82     internal;
83
84     memc_connect_timeout 100ms;
85     memc_send_timeout 100ms;
86     memc_read_timeout 100ms;
87     memc_ignore_client_abort on;
88
89     set $memc_key $query_string;
90     set $memc_exptime 300;
91
92     memc_pass my_memcached;
93 }
94
95 location /foo {
96     set $key $uri$args;
97     srcache_fetch GET /memc $key;
98     srcache_store PUT /memc $key;
99     srcache_store_statuses 200 301 302;
100
101     # proxy_pass/fastcgi_pass/drizzle_pass/echo/etc...
102     # or even static files on the disk
103 }
104```
105
106```nginx
107
108 location = /memc2 {
109     internal;
110
111     memc_connect_timeout 100ms;
112     memc_send_timeout 100ms;
113     memc_read_timeout 100ms;
114     memc_ignore_client_abort on;
115
116     set_unescape_uri $memc_key $arg_key;
117     set $memc_exptime $arg_exptime;
118
119     memc_pass unix:/tmp/memcached.sock;
120 }
121
122 location /bar {
123     set_escape_uri $key $uri$args;
124     srcache_fetch GET /memc2 key=$key;
125     srcache_store PUT /memc2 key=$key&exptime=$srcache_expire;
126
127     # proxy_pass/fastcgi_pass/drizzle_pass/echo/etc...
128     # or even static files on the disk
129 }
130```
131
132```nginx
133
134 map $request_method $skip_fetch {
135     default     0;
136     POST        1;
137     PUT         1;
138 }
139
140 server {
141     listen 8080;
142
143     location /api/ {
144         set $key "$uri?$args";
145
146         srcache_fetch GET /memc $key;
147         srcache_store PUT /memc $key;
148
149         srcache_methods GET PUT POST;
150         srcache_fetch_skip $skip_fetch;
151
152         # proxy_pass/drizzle_pass/content_by_lua/echo/...
153     }
154 }
155```
156
157[Back to TOC](#table-of-contents)
158
159Description
160===========
161
162This module provides a transparent caching layer for arbitrary nginx locations (like those use an upstream or even serve static disk files). The caching behavior is mostly compatible with [RFC 2616](http://www.ietf.org/rfc/rfc2616.txt).
163
164Usually, [memc-nginx-module](https://github.com/openresty/memc-nginx-module) is used together with this module to provide a concrete caching storage backend. But technically, any modules that provide a REST interface can be used as the fetching and storage subrequests used by this module.
165
166For main requests, the [srcache_fetch](#srcache_fetch) directive works at the end of the access phase, so the [standard access module](http://nginx.org/en/docs/http/ngx_http_access_module.html)'s [allow](http://nginx.org/en/docs/http/ngx_http_access_module.html#allow) and [deny](http://nginx.org/en/docs/http/ngx_http_access_module.html#deny) direcives run *before* ours, which is usually the desired behavior for security reasons.
167
168The workflow of this module looks like below:
169
170![srcache flowchart](http://agentzh.org/misc/image/srcache-flowchart.png "srcache flowchart")
171
172[Back to TOC](#table-of-contents)
173
174Subrequest caching
175------------------
176
177For *subrequests*, we explicitly **disallow** the use of this module because it's too difficult to get right. There used to be an implementation but it was buggy and I finally gave up fixing it and abandoned it.
178
179However, if you're using [lua-nginx-module](https://github.com/openresty/lua-nginx-module), it's easy to do subrequest caching in Lua all by yourself. That is, first issue a subrequest to an [memc-nginx-module](https://github.com/openresty/memc-nginx-module) location to do an explicit cache lookup, if cache hit, just use the cached data returned; otherwise, fall back to the true backend, and finally do a cache insertion to feed the data into the cache.
180
181Using this module for main request caching and Lua for subrequest caching is the approach that we're taking in our business. This hybrid solution works great in production.
182
183[Back to TOC](#table-of-contents)
184
185Distributed Memcached Caching
186-----------------------------
187
188Here is a simple example demonstrating a distributed memcached caching mechanism built atop this module. Suppose we do have three different memcached nodes and we use simple modulo to hash our keys.
189
190```nginx
191
192 http {
193     upstream moon {
194         server 10.62.136.54:11211;
195         server unix:/tmp/memcached.sock backup;
196     }
197
198     upstream earth {
199         server 10.62.136.55:11211;
200     }
201
202     upstream sun {
203         server 10.62.136.56:11211;
204     }
205
206     upstream_list universe moon earth sun;
207
208     server {
209         memc_connect_timeout 100ms;
210         memc_send_timeout 100ms;
211         memc_read_timeout 100ms;
212
213         location = /memc {
214             internal;
215
216             set $memc_key $query_string;
217             set_hashed_upstream $backend universe $memc_key;
218             set $memc_exptime 3600; # in seconds
219             memc_pass $backend;
220         }
221
222         location / {
223             set $key $uri;
224             srcache_fetch GET /memc $key;
225             srcache_store PUT /memc $key;
226
227             # proxy_pass/fastcgi_pass/content_by_lua/drizzle_pass/...
228         }
229     }
230 }
231```
232Here's what is going on in the sample above:
2331. We first define three upstreams, `moon`, `earth`, and `sun`. These are our three memcached servers.
2341. And then we group them together as an upstream list entity named `universe` with the `upstream_list` directive provided by [set-misc-nginx-module](https://github.com/openresty/set-misc-nginx-module).
2351. After that, we define an internal location named `/memc` for talking to the memcached cluster.
2361. In this `/memc` location, we first set the `$memc_key` variable with the query string (`$args`), and then use the [set_hashed_upstream](https://github.com/openresty/set-misc-nginx-module#set_hashed_upstream) directive to hash our [$memc_key](https://github.com/openresty/memc-nginx-module#memc_key) over the upsteam list `universe`, so as to obtain a concrete upstream name to be assigned to the variable `$backend`.
2371. We pass this `$backend` variable into the [memc_pass](https://github.com/openresty/memc-nginx-module#memc_pass) directive. The `$backend` variable can hold a value among `moon`, `earth`, and `sun`.
2381. Also, we define the memcached caching expiration time to be 3600 seconds (i.e., an hour) by overriding the [$memc_exptime](https://github.com/openresty/memc-nginx-module#memc_exptime) variable.
2391. In our main public location `/`, we configure the `$uri` variable as our cache key, and then configure [srcache_fetch](#srcache_fetch) for cache lookups and [srcache_store](#srcache_store) for cache updates. We're using two subrequests to our `/memc` location defined earlier in these two directives.
240
241One can use [lua-nginx-module](https://github.com/openresty/lua-nginx-module)'s [set_by_lua](https://github.com/openresty/lua-nginx-module#set_by_lua) or [rewrite_by_lua](https://github.com/openresty/lua-nginx-module#rewrite_by_lua) directives to inject custom Lua code to compute the `$backend` and/or `$key` variables in the sample above.
242
243One thing that should be taken care of is that memcached does have restriction on key lengths, i.e., 250 bytes, so for keys that may be very long, one could use the [set_md5](https://github.com/openresty/set-misc-nginx-module#set_md5) directive or its friends to pre-hash the key to a fixed-length digest before assigning it to `$memc_key` in the `/memc` location or the like.
244
245Further, one can utilize the [srcache_fetch_skip](#srcache_fetch_skip) and [srcache_store_skip](#srcache_store_skip) directives to control what to cache and what not on a per-request basis, and Lua can also be used here in a similar way. So the possibility is really unlimited.
246
247To maximize speed, we often enable TCP (or Unix Domain Socket) connection pool for our memcached upstreams provided by [HttpUpstreamKeepaliveModule](http://wiki.nginx.org/HttpUpstreamKeepaliveModule), for example,
248
249```nginx
250
251 upstream moon {
252     server 10.62.136.54:11211;
253     server unix:/tmp/memcached.sock backup;
254     keepalive 10;
255 }
256```
257
258where we define a connection pool which holds up to 10 keep-alive connections (per nginx worker process) for our `moon` upstream (cluster).
259
260[Back to TOC](#table-of-contents)
261
262Caching with Redis
263------------------
264
265Redis is an alternative key-value store with many additional features.
266
267Here is a working example by using Redis:
268
269```nginx
270
271 location /api {
272     default_type text/css;
273
274     set $key $uri;
275     set_escape_uri $escaped_key $key;
276
277     srcache_fetch GET /redis $key;
278     srcache_store PUT /redis2 key=$escaped_key&exptime=120;
279
280     # fastcgi_pass/proxy_pass/drizzle_pass/postgres_pass/echo/etc
281 }
282
283 location = /redis {
284     internal;
285
286     set_md5 $redis_key $args;
287     redis_pass 127.0.0.1:6379;
288 }
289
290 location = /redis2 {
291     internal;
292
293     set_unescape_uri $exptime $arg_exptime;
294     set_unescape_uri $key $arg_key;
295     set_md5 $key;
296
297     redis2_query set $key $echo_request_body;
298     redis2_query expire $key $exptime;
299     redis2_pass 127.0.0.1:6379;
300 }
301```
302
303This example makes use of the [$echo_request_body](https://github.com/openresty/echo-nginx-module#echo_request_body) variable provided by [echo-nginx-module](https://github.com/openresty/echo-nginx-module). Note that you need the latest version of [echo-nginx-module](https://github.com/openresty/echo-nginx-module), `v0.38rc2` because earlier versions may not work reliably.
304
305Also, you need both [HttpRedisModule](http://wiki.nginx.org/HttpRedisModule) and [redis2-nginx-module](https://github.com/openresty/redis2-nginx-module). The former is used in the [srcache_fetch](#srcache_fetch) subrequest and the latter is used in the [srcache_store](#srcache_store) subrequest.
306
307The Nginx core also has a bug that could prevent [redis2-nginx-module](https://github.com/openresty/redis2-nginx-module)'s pipelining support from working properly in certain extreme conditions. And the following patch fixes this:
308
309   http://mailman.nginx.org/pipermail/nginx-devel/2012-March/002040.html
310
311Note that, however, if you are using the [OpenResty](http://openresty.org/) 1.0.15.3 bundle or later, then you already have everything that you need here in the bundle.
312
313[Back to TOC](#table-of-contents)
314
315Cache Key Preprocessing
316-----------------------
317
318It is often desired to preprocess the cache key to exclude random noises that may hurt the cache hit rate. For example, random session IDs in the URI arguments are usually desired to get removed.
319
320Consider the following URI querystring
321
322    SID=BC3781C3-2E02-4A11-89CF-34E5CFE8B0EF&UID=44332&L=EN&M=1&H=1&UNC=0&SRC=LK&RT=62
323
324we want to remove the `SID` and `UID` arguments from it. It is easy to achieve if you use [lua-nginx-module](https://github.com/openresty/lua-nginx-module) at the same time:
325
326```nginx
327
328 location = /t {
329     rewrite_by_lua '
330         local args = ngx.req.get_uri_args()
331         args.SID = nil
332         args.UID = nil
333         ngx.req.set_uri_args(args)
334     ';
335
336     echo $args;
337 }
338```
339
340Here we use the [echo](https://github.com/openresty/echo-nginx-module#echo) directive from [echo-nginx-module](https://github.com/openresty/echo-nginx-module) to dump out
341the final value of [$args](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_args) in the end. You can replace it with your
342[srcache-nginx-module](https://github.com/openresty/srcache-nginx-module) configurations and upstream configurations instead for
343your case. Let's test this /t interface with curl:
344
345    $ curl 'localhost:8081/t?RT=62&SID=BC3781C3-2E02-4A11-89CF-34E5CFE8B0EF&UID=44332&L=EN&M=1&H=1&UNC=0&SRC=LK'
346    M=1&UNC=0&RT=62&H=1&L=EN&SRC=LK
347
348It is worth mentioning that, if you want to retain the order of the URI
349arguments, then you can do string substitutions on the value of [$args](http://nginx.org/en/docs/http/ngx_http_core_module.html#var_args)
350directly, for example,
351
352    location = /t {
353        rewrite_by_lua '
354            local args = ngx.var.args
355            newargs, n, err = ngx.re.gsub(args, [[\b[SU]ID=[^&]*&?]], "", "jo")
356            if n and n > 0 then
357                ngx.var.args = newargs
358            end
359        ';
360
361        echo $args;
362    }
363
364Now test it with the original curl command again, we get exactly what
365we would expect:
366
367    RT=62&L=EN&M=1&H=1&UNC=0&SRC=LK
368
369But for caching purposes, it's good to normalize the URI argument
370order so that you can increase the cache hit rate. And the hash table
371entry order used by LuaJIT or Lua can be used to normalize the order
372as a nice side effect.
373
374[Back to TOC](#table-of-contents)
375
376Directives
377==========
378
379[Back to TOC](#table-of-contents)
380
381srcache_fetch
382-------------
383**syntax:** *srcache_fetch <method> <uri> <args>?*
384
385**default:** *no*
386
387**context:** *http, server, location, location if*
388
389**phase:** *post-access*
390
391This directive registers an access phase handler that will issue an Nginx subrequest to lookup the cache.
392
393When the subrequest returns status code other than `200`, than a cache miss is signaled and the control flow will continue to the later phases including the content phase configured by [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html), [ngx_http_fastcgi_module](http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html), and others. If the subrequest returns `200 OK`, then a cache hit is signaled and this module will send the subrequest's response as the current main request's response to the client directly.
394
395This directive will always run at the end of the access phase, such that [ngx_http_access_module](http://nginx.org/en/docs/http/ngx_http_access_module.html)'s [allow](http://nginx.org/en/docs/http/ngx_http_access_module.html#allow) and [deny](http://nginx.org/en/docs/http/ngx_http_access_module.html#deny) will always run *before* this.
396
397You can use the [srcache_fetch_skip](#srcache_fetch_skip) directive to disable cache look-up selectively.
398
399[Back to TOC](#table-of-contents)
400
401srcache_fetch_skip
402------------------
403**syntax:** *srcache_fetch_skip <flag>*
404
405**default:** *srcache_fetch_skip 0*
406
407**context:** *http, server, location, location if*
408
409**phase:** *post-access*
410
411The `<flag>` argument supports nginx variables. When this argument's value is not empty *and* not equal to `0`, then the fetching process will be unconditionally skipped.
412
413For example, to skip caching requests which have a cookie named `foo` with the value `bar`, we can write
414
415```nginx
416
417 location / {
418     set $key ...;
419     set_by_lua $skip '
420         if ngx.var.cookie_foo == "bar" then
421             return 1
422         end
423         return 0
424     ';
425
426     srcache_fetch_skip $skip;
427     srcache_store_skip $skip;
428
429     srcache_fetch GET /memc $key;
430     srcache_store GET /memc $key;
431
432     # proxy_pass/fastcgi_pass/content_by_lua/...
433 }
434```
435where [lua-nginx-module](https://github.com/openresty/lua-nginx-module) is used to calculate the value of the `$skip` variable at the (earlier) rewrite phase. Similarly, the `$key` variable can be computed by Lua using the [set_by_lua](https://github.com/openresty/lua-nginx-module#set_by_lua) or [rewrite_by_lua](https://github.com/openresty/lua-nginx-module#rewrite_by_lua) directive too.
436
437The standard [map](http://nginx.org/en/docs/http/ngx_http_map_module.html#map) directive can also be used to compute the value of the `$skip` variable used in the sample above:
438
439```nginx
440
441 map $cookie_foo $skip {
442     default     0;
443     bar         1;
444 }
445```
446
447but your [map](http://nginx.org/en/docs/http/ngx_http_map_module.html#map) statement should be put into the `http` config block in your `nginx.conf` file though.
448
449[Back to TOC](#table-of-contents)
450
451srcache_store
452-------------
453**syntax:** *srcache_store &lt;method&gt; &lt;uri&gt; &lt;args&gt;?*
454
455**default:** *no*
456
457**context:** *http, server, location, location if*
458
459**phase:** *output-filter*
460
461This directive registers an output filter handler that will issue an Nginx subrequest to save the response of the current main request into a cache backend. The status code of the subrequest will be ignored.
462
463You can use the [srcache_store_skip](#srcache_store_skip) and [srcache_store_max_size](#srcache_store_max_size) directives to disable caching for certain requests in case of a cache miss.
464
465Since the `v0.12rc7` release, both the response status line, response headers, and response bodies will be put into the cache. By default, the following special response headers will not be cached:
466
467* Connection
468* Keep-Alive
469* Proxy-Authenticate
470* Proxy-Authorization
471* TE
472* Trailers
473* Transfer-Encoding
474* Upgrade
475* Set-Cookie
476
477You can use the [srcache_store_pass_header](#srcache_store_pass_header) and/or [srcache_store_hide_header](#srcache_store_hide_header) directives to control what headers to cache and what not.
478
479The original response's data chunks get emitted as soon as
480they arrive. `srcache_store` just copies and collects the data in an output filter without postponing them from being sent downstream.
481
482But please note that even though all the response data will be sent immediately, the current Nginx request lifetime will not finish until the srcache_store subrequest completes. That means a delay in closing the TCP connection on the server side (when HTTP keepalive is disabled, but proper HTTP clients should close the connection actively on the client side, which adds no extra delay or other issues at all) or serving the next request sent on the same TCP connection (when HTTP keepalive is in action).
483
484[Back to TOC](#table-of-contents)
485
486srcache_store_max_size
487----------------------
488**syntax:** *srcache_store_max_size &lt;size&gt;*
489
490**default:** *srcache_store_max_size 0*
491
492**context:** *http, server, location, location if*
493
494**phase:** *output-header-filter*
495
496When the response body length is exceeding this size, this module will not try to store the response body into the cache using the subrequest template that is specified in [srcache_store](#srcache_store).
497
498This is particular useful when using a cache storage backend that does have a hard upper limit on the input data. For example, the Memcached server has a default limit of `1 MB` by item.
499
500When `0` is specified (the default value), there's no limit check at all.
501
502[Back to TOC](#table-of-contents)
503
504srcache_store_skip
505------------------
506**syntax:** *srcache_store_skip &lt;flag&gt;*
507
508**default:** *srcache_store_skip 0*
509
510**context:** *http, server, location, location if*
511
512**phase:** *output-header-filter*
513
514The `<flag>` argument supports Nginx variables. When this argument's value is not empty *and* not equal to `0`, then the storing process will be unconditionally skipped.
515
516Starting from the `v0.25` release, the `<flag>` expression (possibly containing Nginx variables) can be evaluated up to twice: the first time is right after the response header is being sent and when the `<flag>` expression is not evaluated to true values it will be evaluated again right after the end of the response body data stream is seen. Before `v0.25`, only the first time evaluation is performed.
517
518Here's an example using Lua to set $nocache to avoid storing URIs that contain the string "/tmp":
519
520```nginx
521
522 set_by_lua $nocache '
523     if string.match(ngx.var.uri, "/tmp") then
524         return 1
525     end
526     return 0';
527
528 srcache_store_skip $nocache;
529```
530
531[Back to TOC](#table-of-contents)
532
533srcache_store_statuses
534----------------------
535**syntax:** *srcache_store_statuses &lt;status1&gt; &lt;status2&gt; ..*
536
537**default:** *srcache_store_statuses 200 301 302*
538
539**context:** *http, server, location, location if*
540
541**phase:** *output-header-filter*
542
543This directive controls what responses to store to the cache according to their status code.
544
545By default, only `200`, `301`, and `302` responses will be stored to cache and any other responses will skip [srcache_store](#srcache_store).
546
547You can specify arbitrary positive numbers for the response status code that you'd like to cache, even including error code like `404` and `503`. For example:
548
549```nginx
550
551 srcache_store_statuses 200 201 301 302 404 503;
552```
553
554At least one argument should be given to this directive.
555
556This directive was first introduced in the `v0.13rc2` release.
557
558[Back to TOC](#table-of-contents)
559
560srcache_store_ranges
561--------------------
562**syntax:** *srcache_store_ranges on|off*
563
564**default:** *srcache_store_ranges off*
565
566**context:** *http, server, location, location if*
567
568**phase:** *output-body-filter*
569
570When this directive is turned on (default to `off`), [srcache_store](#srcache_store) will also store 206 Partial Content responses generated by the standard `ngx_http_range_filter_module`. If you turn this directive on, you MUST add `$http_range` to your cache keys. For example,
571
572```nginx
573
574 location / {
575     set $key "$uri$args$http_range";
576     srcache_fetch GET /memc $key;
577     srcache_store PUT /memc $key;
578 }
579```
580
581This directive was first introduced in the `v0.27` release.
582
583[Back to TOC](#table-of-contents)
584
585srcache_header_buffer_size
586--------------------------
587**syntax:** *srcache_header_buffer_size &lt;size&gt;*
588
589**default:** *srcache_header_buffer_size 4k/8k*
590
591**context:** *http, server, location, location if*
592
593**phase:** *output-header-filter*
594
595This directive controles the header buffer when serializing response headers for [srcache_store](#srcache_store). The default size is the page size, usually `4k` or `8k` depending on specific platforms.
596
597Note that the buffer is not used to hold all the response headers, but just each individual header. So the buffer is merely needed to be big enough to hold the longest response header.
598
599This directive was first introduced in the `v0.12rc7` release.
600
601[Back to TOC](#table-of-contents)
602
603srcache_store_hide_header
604-------------------------
605**syntax:** *srcache_store_hide_header &lt;header&gt;*
606
607**default:** *no*
608
609**context:** *http, server, location, location if*
610
611**phase:** *output-header-filter*
612
613By default, this module caches all the response headers except the following ones:
614
615* Connection
616* Keep-Alive
617* Proxy-Authenticate
618* Proxy-Authorization
619* TE
620* Trailers
621* Transfer-Encoding
622* Upgrade
623* Set-Cookie
624
625You can hide even more response headers from [srcache_store](#srcache_store) by listing their names (case-insensitive) by means of this directive. For examples,
626
627```nginx
628
629 srcache_store_hide_header X-Foo;
630 srcache_store_hide_header Last-Modified;
631```
632
633Multiple occurrences of this directive are allowed in a single location.
634
635This directive was first introduced in the `v0.12rc7` release.
636
637See also [srcache_store_pass_header](#srcache_store_pass_header).
638
639[Back to TOC](#table-of-contents)
640
641srcache_store_pass_header
642-------------------------
643**syntax:** *srcache_store_pass_header &lt;header&gt;*
644
645**default:** *no*
646
647**context:** *http, server, location, location if*
648
649**phase:** *output-header-filter*
650
651By default, this module caches all the response headers except the following ones:
652
653* Connection
654* Keep-Alive
655* Proxy-Authenticate
656* Proxy-Authorization
657* TE
658* Trailers
659* Transfer-Encoding
660* Upgrade
661* Set-Cookie
662
663You can force [srcache_store](#srcache_store) to store one or more of these response headers from [srcache_store](#srcache_store) by listing their names (case-insensitive) by means of this directive. For examples,
664
665```nginx
666
667 srcache_store_pass_header Set-Cookie;
668 srcache_store_pass_header Proxy-Autenticate;
669```
670
671Multiple occurrences of this directive are allowed in a single location.
672
673This directive was first introduced in the `v0.12rc7` release.
674
675See also [srcache_store_hide_header](#srcache_store_hide_header).
676
677[Back to TOC](#table-of-contents)
678
679srcache_methods
680---------------
681**syntax:** *srcache_methods &lt;method&gt;...*
682
683**default:** *srcache_methods GET HEAD*
684
685**context:** *http, server, location*
686
687**phase:** *post-access, output-header-filter*
688
689This directive specifies HTTP request methods that are considered by either [srcache_fetch](#srcache_fetch) or [srcache_store](#srcache_store). HTTP request methods not listed will be skipped completely from the cache.
690
691The following HTTP methods are allowed: `GET`, `HEAD`, `POST`, `PUT`, and `DELETE`. The `GET` and `HEAD` methods are always implicitly included in the list regardless of their presence in this directive.
692
693Note that since the `v0.17` release `HEAD` requests are always skipped by [srcache_store](#srcache_store) because their responses never carry a response body.
694
695This directive was first introduced in the `v0.12rc7` release.
696
697[Back to TOC](#table-of-contents)
698
699srcache_ignore_content_encoding
700-------------------------------
701**syntax:** *srcache_ignore_content_encoding on|off*
702
703**default:** *srcache_ignore_content_encoding off*
704
705**context:** *http, server, location, location if*
706
707**phase:** *output-header-filter*
708
709When this directive is turned `off` (which is the default), non-empty `Content-Encoding` response header will cause [srcache_store](#srcache_store) skip storing the whole response into the cache and issue a warning into nginx's `error.log` file like this:
710
711
712    [warn] 12500#0: *1 srcache_store skipped due to response header "Content-Encoding: gzip"
713                (maybe you forgot to disable compression on the backend?)
714
715
716Turning on this directive will ignore the `Content-Encoding` response header and store the response as usual (and also without warning).
717
718It's recommended to always disable gzip/deflate compression on your backend server by specifying the following line in your `nginx.conf` file:
719
720```nginx
721
722 proxy_set_header  Accept-Encoding  "";
723```
724
725This directive was first introduced in the `v0.12rc7` release.
726
727[Back to TOC](#table-of-contents)
728
729srcache_request_cache_control
730-----------------------------
731**syntax:** *srcache_request_cache_control on|off*
732
733**default:** *srcache_request_cache_control off*
734
735**context:** *http, server, location*
736
737**phase:** *post-access, output-header-filter*
738
739When this directive is turned `on`, the request headers `Cache-Control` and `Pragma` will be honored by this module in the following ways:
740
7411. [srcache_fetch](#srcache_fetch), i.e., the cache lookup operation, will be skipped when request headers `Cache-Control: no-cache` and/or `Pragma: no-cache` are present.
7421. [srcache_store](#srcache_store), i.e., the cache store operation, will be skipped when the request header `Cache-Control: no-store` is specified.
743
744Turning off this directive will disable this functionality and is considered safer for busy sites mainly relying on cache for speed.
745
746This directive was first introduced in the `v0.12rc7` release.
747
748See also [srcache_response_cache_control](#srcache_response_cache_control).
749
750[Back to TOC](#table-of-contents)
751
752srcache_response_cache_control
753------------------------------
754**syntax:** *srcache_response_cache_control on|off*
755
756**default:** *srcache_response_cache_control on*
757
758**context:** *http, server, location*
759
760**phase:** *output-header-filter*
761
762When this directive is turned `on`, the response headers `Cache-Control` and `Expires` will be honored by this module in the following ways:
763
764* `Cache-Control: private` skips [srcache_store](#srcache_store),
765* `Cache-Control: no-store` skips [srcache_store](#srcache_store),
766* `Cache-Control: no-cache` skips [srcache_store](#srcache_store),
767* `Cache-Control: max-age=0` skips [srcache_store](#srcache_store),
768* and `Expires: <date-no-more-recently-than-now>` skips [srcache_store](#srcache_store).
769
770This directive takes priority over the [srcache_store_no_store](#srcache_store_no_store), [srcache_store_no_cache](#srcache_store_no_cache), and [srcache_store_private](#srcache_store_private) directives.
771
772This directive was first introduced in the `v0.12rc7` release.
773
774See also [srcache_request_cache_control](#srcache_request_cache_control).
775
776[Back to TOC](#table-of-contents)
777
778srcache_store_no_store
779----------------------
780**syntax:** *srcache_store_no_store on|off*
781
782**default:** *srcache_store_no_store off*
783
784**context:** *http, server, location*
785
786**phase:** *output-header-filter*
787
788Turning this directive on will force responses with the header `Cache-Control: no-store` to be stored into the cache when [srcache_response_cache_control](#srcache_response_cache_control) is turned `on` *and* other conditions are met. Default to `off`.
789
790This directive was first introduced in the `v0.12rc7` release.
791
792[Back to TOC](#table-of-contents)
793
794srcache_store_no_cache
795----------------------
796**syntax:** *srcache_store_no_cache on|off*
797
798**default:** *srcache_store_no_cache off*
799
800**context:** *http, server, location*
801
802**phase:** *output-header-filter*
803
804Turning this directive on will force responses with the header `Cache-Control: no-cache` to be stored into the cache when [srcache_response_cache_control](#srcache_response_cache_control) is turned `on` *and* other conditions are met. Default to `off`.
805
806This directive was first introduced in the `v0.12rc7` release.
807
808[Back to TOC](#table-of-contents)
809
810srcache_store_private
811---------------------
812**syntax:** *srcache_store_private on|off*
813
814**default:** *srcache_store_private off*
815
816**context:** *http, server, location*
817
818**phase:** *output-header-filter*
819
820Turning this directive on will force responses with the header `Cache-Control: private` to be stored into the cache when [srcache_response_cache_control](#srcache_response_cache_control) is turned `on` *and* other conditions are met. Default to `off`.
821
822This directive was first introduced in the `v0.12rc7` release.
823
824[Back to TOC](#table-of-contents)
825
826srcache_default_expire
827----------------------
828**syntax:** *srcache_default_expire &lt;time&gt;*
829
830**default:** *srcache_default_expire 60s*
831
832**context:** *http, server, location, location if*
833
834**phase:** *output-header-filter*
835
836This directive controls the default expiration time period that is allowed for the [$srcache_expire](#srcache_expire) variable value when neither `Cache-Control: max-age=N` nor `Expires` are specified in the response headers.
837
838The `<time>` argument values are in seconds by default. But it's wise to always explicitly specify the time unit to avoid confusion. Time units supported are "s"(seconds), "ms"(milliseconds), "y"(years), "M"(months), "w"(weeks), "d"(days), "h"(hours), and "m"(minutes). For example,
839
840```nginx
841
842 srcache_default_expire 30m; # 30 minutes
843```
844
845This time must be less than 597 hours.
846
847The semantics of a zero expiration time depends on the actual cache backend storage you are currently using, which is agnostic to this
848module. In the case of memcached, for example, zero expiration times mean that the item will never expire.
849
850This directive was first introduced in the `v0.12rc7` release.
851
852[Back to TOC](#table-of-contents)
853
854srcache_max_expire
855------------------
856**syntax:** *srcache_max_expire &lt;time&gt;*
857
858**default:** *srcache_max_expire 0*
859
860**context:** *http, server, location, location if*
861
862**phase:** *output-header-filter*
863
864This directive controls the maximal expiration time period that is allowed for the [$srcache_expire](#srcache_expire) variable value. This setting takes priority over other calculating methods.
865
866The `<time>` argument values are in seconds by default. But it's wise to always explicitly specify the time unit to avoid confusion. Time units supported are "s"(seconds), "ms"(milliseconds), "y"(years), "M"(months), "w"(weeks), "d"(days), "h"(hours), and "m"(minutes). For example,
867
868```nginx
869
870 srcache_max_expire 2h;  # 2 hours
871```
872
873This time must be less than 597 hours.
874
875When `0` is specified, which is the default setting, then there will be *no* limit at all.
876
877This directive was first introduced in the `v0.12rc7` release.
878
879[Back to TOC](#table-of-contents)
880
881Variables
882=========
883[Back to TOC](#table-of-contents)
884
885$srcache_expire
886---------------
887**type:** *integer*
888
889**cacheable:** *no*
890
891**writable:** *no*
892
893This Nginx variable gives the recommended expiration time period (in seconds) for the current response being stored into the cache. The algorithm of computing the value is as follows:
894
8951. When the response header `Cache-Control: max-age=N` is specified, then `N` will be used as the expiration time,
8961. otherwise if the response header `Expires` is specified, then the expiration time will be obtained by subtracting the current time stamp from the time specified in the `Expires` header,
8971. when neither `Cache-Control: max-age=N` nor `Expires` headers are specified, use the value specified in the [srcache_default_expire](#srcache_default_expire) directive.
898
899The final value of this variable will be the value specified by the [srcache_max_expire](#srcache_max_expire) directive if the value obtained in the algorithm above exceeds the maximal value (if any).
900
901You don't have to use this variable for the expiration time.
902
903This variable was first introduced in the `v0.12rc7` release.
904
905[Back to TOC](#table-of-contents)
906
907$srcache_fetch_status
908---------------------
909**type:** *string*
910
911**cacheable:** *no*
912
913**writable:** *no*
914
915This Nginx variable is evaluated to the status of the "fetch" phase for the caching system. Three values are possible, `HIT`, `MISS`, and `BYPASS`.
916
917When the "fetch" subrequest returns status code other than `200` or its response data is not well-formed, then this variable is evaluated to the value `MISS`.
918
919The value of this variable is only meaningful after the `access` request processing phase, or `BYPASS` is always given.
920
921This variable was first introduced in the `v0.14` release.
922
923[Back to TOC](#table-of-contents)
924
925$srcache_store_status
926---------------------
927**type:** *string*
928
929**cacheable:** *no*
930
931**writable:** *no*
932
933This Nginx variable gives the current caching status for the "store" phase. Two possible values, `STORE` and `BYPASS` can be obtained.
934
935Because the responses for the "store" subrequest are always discarded, so the value of this variable will always be `STORE` as long as the "store" subrequest is actually issued.
936
937The value of this variable is only meaningful at least when the request headers of the current (main) request are being sent. The final result can only be obtained after all the response body has been sent if the `Content-Length` response header is not specified for the main request.
938
939This variable was first introduced in the `v0.14` release.
940
941[Back to TOC](#table-of-contents)
942
943Known Issues
944============
945* On certain systems, enabling aio and/or sendfile may stop [srcache_store](#srcache_store) from working. You can disable them in the locations configured by [srcache_store](#srcache_store).
946* The [srcache_store](#srcache_store) directive can not be used to capture the responses generated by [echo-nginx-module](https://github.com/openresty/echo-nginx-module)'s subrequest directivees like [echo_subrequest_async](https://github.com/openresty/echo-nginx-module#echo_subrequest_async) and [echo_location](https://github.com/openresty/echo-nginx-module#echo_location). You are recommended to use HttpLuaModule to initiate and capture subrequests, which should work with [srcache_store](#srcache_store).
947
948[Back to TOC](#table-of-contents)
949
950Caveats
951=======
952* It is recommended to disable your backend server's gzip compression and use nginx's [ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module.html) to do the job. In case of [ngx_http_proxy_module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html), you can use the following configure setting to disable backend gzip compression:
953```nginx
954
955 proxy_set_header  Accept-Encoding  "";
956```
957* Do *not* use [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html)'s [if](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#if) directive in the same location as this module's, because "[if](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#if) is evil". Instead, use [ngx_http_map_module](http://nginx.org/en/docs/http/ngx_http_map_module.html) or [lua-nginx-module](https://github.com/openresty/lua-nginx-module) combined with this module's [srcache_store_skip](#srcache_store_skip) and/or [srcache_fetch_skip](#srcache_fetch_skip) directives. For example:
958```nginx
959
960 map $request_method $skip_fetch {
961     default     0;
962     POST        1;
963     PUT         1;
964 }
965
966 server {
967     listen 8080;
968
969     location /api/ {
970         set $key "$uri?$args";
971
972         srcache_fetch GET /memc $key;
973         srcache_store PUT /memc $key;
974
975         srcache_methods GET PUT POST;
976         srcache_fetch_skip $skip_fetch;
977
978         # proxy_pass/drizzle_pass/content_by_lua/echo/...
979     }
980 }
981```
982
983[Back to TOC](#table-of-contents)
984
985Trouble Shooting
986================
987
988To debug issues, you should always check your Nginx `error.log` file first. If no error messages are printed, you need to enable the Nginx debugging logs to get more details, as explained in [debugging log](http://nginx.org/en/docs/debugging_log.html).
989
990Several common pitfalls for beginners:
991
992* The original response carries a `Cache-Control` header that explicitly disables caching and you do not configure directives like [srcache_response_cache_control](#srcache_response_cache_control).
993* The original response is already gzip compressed, which is not cached by default (see [srcache_ignore_content_encoding](#srcache_ignore_content_encoding)).
994* Memcached might return `CLIENT_ERROR bad command line format` when using a too long key (250 chars as of version 1.4.25). It is thus safer to use `set_md5 $key $uri$args;` instead of `set $key $uri$args;`. The `set_md5` directive (and more) is available from [OpenResty's set-misc module](https://github.com/openresty/set-misc-nginx-module).
995* Nginx might return `client intended to send too large body` when trying to store objects larger than 1m to the storage backend, in which case nginx `client_max_body_size` must be set to a higher value.
996* Memcached might fail to store objects larger than 1m, causing errors like `srcache_store subrequest failed status=502`. Since version 1.4.2, memcached supports a command-line `-I` option to override the default size of each slab page. Please read its manpage for more information.
997
998[Back to TOC](#table-of-contents)
999
1000Installation
1001============
1002
1003It is recommended to install this module as well as the Nginx core and many other goodies via the [OpenResty bundle](http://openresty.org). It is the easiest way and most safe way to set things up. See OpenResty's [installation instructions](http://openresty.org/#Installation) for details.
1004
1005Alternatively, you can build Nginx with this module all by yourself:
1006
1007* Grab the nginx source code from [nginx.org](http://nginx.org), for example, the version 1.9.15 (see [Nginx Compatibility](#compatibility)),
1008* and then apply the patch to your nginx source tree that fixes an important bug in the mainline Nginx core: <https://raw.github.com/openresty/openresty/master/patches/nginx-1.4.3-upstream_truncation.patch> (you do NOT need this patch if you are using nginx 1.5.3 and later versions.)
1009* after that, download the latest version of the release tarball of this module from srcache-nginx-module [file list](https://github.com/openresty/srcache-nginx-module/tags),
1010* and finally build the Nginx source with this module
1011
1012```bash
1013 wget 'http://nginx.org/download/nginx-1.9.15.tar.gz'
1014 tar -xzvf nginx-1.9.15.tar.gz
1015 cd nginx-1.9.15/
1016
1017 # Here we assume you would install you nginx under /opt/nginx/.
1018 ./configure --prefix=/opt/nginx \
1019      --add-module=/path/to/srcache-nginx-module
1020
1021 make -j2
1022 make install
1023```
1024
1025Starting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the `--add-dynamic-module=PATH` option instead of `--add-module=PATH` on the
1026`./configure` command line above. And then you can explicitly load the module in your `nginx.conf` via the [load_module](http://nginx.org/en/docs/ngx_core_module.html#load_module)
1027directive, for example,
1028
1029```nginx
1030load_module /path/to/modules/ngx_http_srcache_filter_module.so;
1031```
1032
1033[Back to TOC](#table-of-contents)
1034
1035Compatibility
1036=============
1037
1038The following versions of Nginx should work with this module:
1039
1040* 1.9.x (last tested: 1.9.15)
1041* 1.8.x
1042* 1.7.x (last tested: 1.7.10)
1043* 1.5.x (last tested: 1.5.12)
1044* 1.4.x (last tested: 1.4.4)
1045* 1.3.x (last tested: 1.3.7)
1046* 1.2.x (last tested: 1.2.9)
1047* 1.1.x (last tested: 1.1.5)
1048* 1.0.x (last tested: 1.0.11)
1049* 0.9.x (last tested: 0.9.4)
1050* 0.8.x >= 0.8.54 (last tested: 0.8.54)
1051
1052Earlier versions of Nginx like 0.7.x, 0.6.x and 0.5.x will *not* work.
1053
1054If you find that any particular version of Nginx above 0.7.44 does not work with this module, please consider reporting a bug.
1055
1056[Back to TOC](#table-of-contents)
1057
1058Community
1059=========
1060
1061[Back to TOC](#table-of-contents)
1062
1063English Mailing List
1064--------------------
1065
1066The [openresty-en](https://groups.google.com/group/openresty-en) mailing list is for English speakers.
1067
1068[Back to TOC](#table-of-contents)
1069
1070Chinese Mailing List
1071--------------------
1072
1073The [openresty](https://groups.google.com/group/openresty) mailing list is for Chinese speakers.
1074
1075[Back to TOC](#table-of-contents)
1076
1077Bugs and Patches
1078================
1079
1080Please submit bug reports, wishlists, or patches by
1081
10821. creating a ticket on the [GitHub Issue Tracker](https://github.com/openresty/srcache-nginx-module/issues),
10831. or posting to the [OpenResty community](#community).
1084
1085[Back to TOC](#table-of-contents)
1086
1087Source Repository
1088=================
1089Available on github at [openresty/srcache-nginx-module](https://github.com/openresty/srcache-nginx-module).
1090
1091[Back to TOC](#table-of-contents)
1092
1093Test Suite
1094==========
1095This module comes with a Perl-driven test suite. The [test cases](https://github.com/openresty/srcache-nginx-module/tree/master/test/t) are [declarative](https://github.com/openresty/srcache-nginx-module/blob/master/test/t/main-req.t) too. Thanks to the [Test::Nginx](http://search.cpan.org/perldoc?Test::Base) module in the Perl world.
1096
1097To run it on your side:
1098```bash
1099
1100 $ PATH=/path/to/your/nginx-with-srcache-module:$PATH prove -r t
1101```
1102You need to terminate any Nginx processes before running the test suite if you have changed the Nginx server binary.
1103
1104Because a single nginx server (by default, `localhost:1984`) is used across all the test scripts (`.t` files), it's meaningless to run the test suite in parallel by specifying `-jN` when invoking the `prove` utility.
1105
1106Some parts of the test suite requires modules [ngx_http_rewrite_module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html), [echo-nginx-module](https://github.com/openresty/echo-nginx-module), [rds-json-nginx-module](https://github.com/openresty/rds-json-nginx-module), and [drizzle-nginx-module](https://github.com/openresty/drizzle-nginx-module) to be enabled as well when building Nginx.
1107
1108[Back to TOC](#table-of-contents)
1109
1110TODO
1111====
1112* add gzip compression and decompression support.
1113* add new nginx variable `$srcache_key` and new directives `srcache_key_ignore_args`, `srcache_key_filter_args`, and `srcache_key_sort_args`.
1114
1115[Back to TOC](#table-of-contents)
1116
1117Getting involved
1118================
1119You'll be very welcomed to submit patches to the author or just ask for a commit bit to the source repository on GitHub.
1120
1121[Back to TOC](#table-of-contents)
1122
1123Author
1124======
1125Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>, CloudFlare Inc.
1126
1127[Back to TOC](#table-of-contents)
1128
1129Copyright & License
1130===================
1131
1132Copyright (c) 2010-2016, Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>, CloudFlare Inc.
1133
1134This module is licensed under the terms of the BSD license.
1135
1136Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1137
1138* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
1139* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
1140
1141THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1142
1143[Back to TOC](#table-of-contents)
1144
1145See Also
1146========
1147* [memc-nginx-module](https://github.com/openresty/memc-nginx-module)
1148* [lua-nginx-module](https://github.com/openresty/lua-nginx-module)
1149* [set-misc-nginx-module](https://github.com/openresty/set-misc-nginx-module)
1150* The [openresty bundle](http://openresty.org)
1151
1152[Back to TOC](#table-of-contents)
1153
1154