【问题标题】:Nginx - turn an $arg_ into a path with 3 subdirectories for try_filesNginx - 将 $arg_ 转换为包含 try_files 的 3 个子目录的路径
【发布时间】:2017-10-19 11:53:16
【问题描述】:

我目前正在使用 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 将生成图像。这没有问题。

现在对于给我带来麻烦的部分,服务器应该提供的第二种图像通常更大并且是基于多个参数@987654326创建的@。

这些图像可以通过生成的哈希来识别,该哈希始终为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,确保生成图像?

【问题讨论】:

  • 您无法测试 location 表达式中的参数。 location 和 rewrite 指令使用规范化的 URI,不包括 ? 及其后的任何内容。
  • @RichardSmith 有道理,参数不是位置。如果我将location ~* ... 更改为location = /image.php,我可以在位置块内的if 语句中对$arg_hash 进行正则表达式吗?还是应该换一种方式?
  • 您可以使用if,但您将无法使用try_files。你还在坚持/image.php?hash= 风格的请求吗?
  • 是的,恐怕是这样,这主要是为了替代现有的图像缓存服务器,这个“版本”中的新功能是图像的整个子目录位置。

标签: nginx nginx-location


【解决方案1】:

你可以使用类似下面的东西

http {

    map $arg_hash $arg_hash_folder {

        default '';
        ~*(.)(.)(.)(.*)$ /$1/$2/$3/$1$2$3$4.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处理代码又来了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多