Nginx - 将 $arg_ 转换为包含 try_files 的 3 个子目录的路径

Nginx - turn an $arg_ into a path with 3 subdirectories for try_files

我目前正在使用 Nginx 开发图像缓存服务器,但是我 运行 遇到 让 Nginx 为缓存服务提供服务的问题图片

缓存服务器应该能够提供两种图像,第一种是相当小的图像,它们几乎不需要图像服务器的干扰。

这按照我想要的方式工作,使用以下配置:

location = /small/ {
  try_files /small/logos/$arg_id.jpg @gen_script;
}
location @gen_script {
  rewrite ^(.*)$ /small/index.php?id=$arg_id;
}

这里没问题,使用此配置,它会尝试在目录 /small/logos 中查找名称与提供的 ID-parameter 匹配的图像,如果不存在,则引用 @gen_script,那个导致 index.php 将生成图像。这没有问题。

现在对于给我带来麻烦的部分,服务器应该提供的第二种图像一般较大并且基于多个参数 (height, width, that sort of thing) 创建。

这些图像 可以通过生成的散列 进行识别,该散列总是 128 characters long

我想要实现的是将散列的前三个字符转换为可以找到图像的路径的目录,然后是 完整的散列和“.jpg” 。这是这方面的配置,它不起作用,我不知道为什么:

location ~* "^\/image\.php\?hash=(?<a>.{1})(?<b>.{1})(?<c>.{1})(?<d>.{125})(?:.+)$" {
  try_files /images/$a/$b/$c/$a$b$c$d.jpg @image_gen;
}
location @image_gen {
  rewrite ^(.*)$ /image.php$is_args$args;
}

与预期的行为相反,对 image.php 的每个请求实际上都被 image.php 接收(或发送到),再次创建请求的图像,与(或任何...)缓存服务器应该做

为澄清起见,如果哈希为 abcde12345(为了便于阅读而缩短),则图像将位于 /images/a/b/c/abcde12345.jpg。 我如何确保 try_files 检查文件是否存在于预期的子目录结构中,如果不存在,则将原始请求及其参数转发给 /image.php,确保生成图像?

您可以使用类似下面的内容

http {

    map $arg_hash $arg_hash_folder {

        default '';
        ~*(.)(.)(.)(.*)$ ////.jpg;
    }

    server {

        location = /image.php {

            try_files $arg_hash_folder @process_image;
        }

        location @process_image {

            # Try rewrite here and see if it works
            # If it doesn't work then you should have the php processing code here
            # fastcgi_pass ....;
        }
    }
}

地图将为您提供文件夹路径,如果未找到,将调用 process_image,您可以在此处尝试重写,我怀疑这是否可行,因此您需要包含PHP 再次处理代码