How to determine when the response from the cache

Hello!

Can you please tell how to cope with this task.
When nginx gives directly the page, add the title “backend_id”.
And when it taking from the cache, don’t add the header.

The scheme works like this:
Frontend - nginx with proxy_cache, followed by multiple backends
(proxy_pass to multiple servers).
I need to distinguish, when a response from the cache and when it from
the backend.
If the response from the backend, i need to understand from which
backend he came.
Backends configured to add a response header backend_id.
But the frontend caches the entire response, with headers.
As a result, you can understand which backend was generated response.
But i can’t see, is it direct response, or from the cache.

Are there ways to cope with this task?
Need your wise advice.

Posted at Nginx Forum:

Hi,

you can set 3 headers in this case (I’m doing the same for my front end
server).

Those two to understand which backend server served the request and
which HTTP status it responded with.
add_header X-AppServer $upstream_addr; # Backend Server / Port
add_header X-AppServer-Status $upstream_status; # Backend HTTP Status

To understand if the request was served from the Proxy Cache you can use
add_header X-Cache $upstream_cache_status; # HIT / MISS / BYPASS /
EXPIRED

The header ‘X-Cache’ will only be sent in case it does have a value. So
you won’t see that in case the response was not served by the proxy
cache. A ‘Age’ header to determine how old the object is isn’t
implemented currently (I opened an Issue re/ that a while ago).

In addition to the Headers you can easily log all Requests to your Proxy
to another access_log which will contain all those information for
central monitoring. That could look like the one here:

Regards,
Chris

Am 12.05.2012 um 13:03 schrieb xore:

Chris, thank you, this is what i need.

By the way, i found one strange thing - operator “if” don’t work with
$upstream_cache_status.
For example, i try to change “HIT” and “MISS” to more enigmatic values

set $tocache X;
if ($upstream_cache_status = HIT)
{
set $tocache H;
}

if ($upstream_cache_status = MISS)
{
set $tocache M;
}

add_header tocache “$tocache ($upstream_cache_status)”;

I expected to see “tocache: M (MISS)” and “tocache: H (HIT)”.
But i got “tocache: X (MISS)” and “tocache: X (HIT)”.

Maybe “if” works not for any variable?

Posted at Nginx Forum:

“if” (as operator of module “rewrite”) works before server gets answer
from upstream.
That’s why $upstream_* variables are empty for him.
In my case operator “map” helps me.

Posted at Nginx Forum: