【问题标题】:What does Nginx take into account when caching a request?Nginx 在缓存请求时会考虑什么?
【发布时间】:2023-02-03 15:30:30
【问题描述】:

Nginx 在缓存请求时会考虑除 url 之外的哪些属性(headers,cookies)?

我试图在nginx/日志/access.log文件。我只找到了有关发出的请求类型 (GET) 及其状态(404、200 等)的信息。

这是我的nginx 配置文件文件:

#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";
        }
    }
}

【问题讨论】:

    标签: nginx caching nginx-cache


    【解决方案1】:

    Nginx 在缓存请求时会考虑什么?

    完整网址

    Nginx 在缓存请求时使用的相关配置是proxy_cache_key

    语法:proxy_cache_key 字符串;

    默认值:proxy_cache_key $scheme$proxy_host$request_uri;

    上下文:http、服务器、位置

    定义用于缓存的键,例如

    proxy_cache_key "$host$request_uri $cookie_user"; 
    

    默认情况下, 指令的值接近字符串

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

    所以默认情况下,Nginx 在缓存请求时不考虑任何标头,只考虑完整的 url(使用 get Args)

    如何自定义缓存键

    自定义缓存键只需要使用proxy_cache_key指令。

    要基于 cookie 值进行缓存,文档中已经有一个示例 - 但我建议:

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

    为什么要在密钥中添加更多文本?考虑一下如果您像这样使用多个 cookie 会发生什么:

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

    它避免了只有 $cookie_group 的请求与仅在 $cookie_user 中具有相同值的缓存内容发生冲突的可能性。如果您需要查看,还可以更轻松地了解磁盘上的文件包含的内容。

    如果您想使用任意标头 - 只需包含 the variable for that header 例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 2017-02-15
      • 2016-10-30
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多