Forwarding request when serving from NGINX cache – Is this possible?

Suhail Gupta asked:

I have enabled caching with Nginx. I followed the official docs and it works fine. What happens is, when the request comes in for the first time, it is proxy passed to a server. The response is cached.

From there on, all requests are served from the Nginx cache until it expires. But I want an additional thing.

Here is what I want:

  1. When the request is served from the cache, I want to make an API request to my server so that I do not loose on the number of hits (counter)

How can I do this?

I had tried the mirror command, but it does not get called when the page is served from cache. It only gets called when the cache expires. Here is the config snapshot that I tried. Is this even possible? Any other way to do this?

enter image description here

Cache directive as highlighted in the second screenshot.

enter image description here

My answer:

This doesn’t appear to be possible. The mirror directive is processed as a subrequest to the original request, so if nginx does not process the original request, the mirror request will also not be processed.

As a workaround, you can add a second custom access_log directive, which uses a custom log_format. Your program can then read this log to determine when a cache hit occurred and to which URL. In fact, it could just use that log to count all hits, cached or not.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.