Nginx open_file_cache如何使一个文件无效(清除)

zzwlnbp8  于 2022-12-03  发布在  Nginx
关注(0)|答案(1)|浏览(153)

例如,我们在/etc/nginx/nginx.conf中启用了open_file_cache:

open_file_cache max=10000 inactive=60s;
open_file_cache_valid    60s;
open_file_cache_min_uses 2;
open_file_cache_errors   on;

有些文件/my/file. jpg被更改了,我们知道它在服务器端。示例位置块,点击这个文件:

location ~ (.+)\.[^\.][^\.][^\.]?[^\.]?[^\.]?[^\.]?$
{
    include /etc/nginx/upload.mime.types;
    add_header Access-Control-Allow-Origin *;
    root                               $hostdir;
    try_files                          $uri =404;
    error_page 404 /public/404.png;
}

如何清除服务器端的缓存?

7hiiyaii

7hiiyaii1#

您可以将特殊参数识别添加到文件请求中。如果传递了此参数,则需要设置选项open_file_cache_valid 0s。例如:

location ~ (.+)\.[^\.][^\.][^\.]?[^\.]?[^\.]?[^\.]?$
{
    include /etc/nginx/upload.mime.types;
    error_page 419 = @purgecache;
    add_header Access-Control-Allow-Origin *;
    if ($arg_purgecache) {
        #directly set "open_file_cache off;" here not works, don't know why
        return 419;
    }
    root                               $hostdir;
    try_files                          $uri =404;
    error_page 404 /public/404.png;
}

location @purgecache
{
    open_file_cache_valid 0s;
    root                               $hostdir;
    try_files                          $uri =404;
    error_page 404 /public/404.png;
}

在后端(例如PHP)-只需添加url purgecache参数。但值需要随机化,以禁用浏览器缓存:

<img src="/my/file.jpg?purgecache=<?=rand(1000,1000000000)?>">

或仅服务器端清除:

file_get_contents(__DIR__ . "/my/file.jpg?purgecache=".rand(1000,1000000000));

相关问题