Home > other >  What does Nginx take into account when caching a request?
What does Nginx take into account when caching a request?

Time:02-03

What attributes(headers, cookies) besides url does Nginx take into account when caching a request?

I was trying to find out this information in nginx/log/access.log file. I have found only information about what type of request had been made(GET) and its status(404, 200, etc.).

Here my nginx.conf file:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid logs/nginx.pid;
    
events {
    worker_connections  1024;
}

# MY TEST SERVER
http {
    # CACHE
    proxy_cache_path "C:\data\cache" levels=1:2 keys_zone=all:32m;

    server {
        listen 80;
        location / {
            proxy_pass http://127.0.0.1:81/;
            proxy_cache all;
            proxy_cache_valid 404 502 503 1s;
            proxy_cache_valid any 10s;
        }
      
    server {
        listen 81;
        location / {
            root "C:\data\www";
        }
        location /images/ {
            root "C:\data";
        }
    }
}

CodePudding user response:

What does Nginx take into account when caching a request?

The full URL

The relevant config for what Nginx uses when caching a request is proxy_cache_key

Syntax: proxy_cache_key string;

Default: proxy_cache_key $scheme$proxy_host$request_uri;

Context: http, server, location

Defines a key for caching, for example

proxy_cache_key "$host$request_uri $cookie_user"; 

By default, the directive’s value is close to the string

proxy_cache_key $scheme$proxy_host$uri$is_args$args;

So by default Nginx does not take into account any headers when caching a request, only the full url (with get Args)

How to customize the cache key

To customize the cache key only requires using the proxy_cache_key directive.

To cache based on a cookie value, there's already an example in the documentation - but I suggest:

proxy_cache_key "$host$request_uri:u:$cookie_user";

Why add more text to the key? Consider what happens if you use multiple cookies like so:

proxy_cache_key "$host$request_uri:u:$cookie_user:g:$cookie_group";

It avoids the possibility of a request with only $cookie_group colliding with the cached content for something with the same value only in $cookie_user. It also makes it easier to understand what the files on disk contain, if you have the need to look.

If you want to use an arbitrary header - just include the variable for that header e.g.:

proxy_cache_key "$host$request_uri:n:$http_name";
  • Related