Nginx的 - 把一个$ arg_成路3个子目录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及其参数,确保生成映像?

+0

您无法测试'location'表达式中的参数。 'location'和'rewrite'指令使用规范化的URI,它不包含'?'及其后的任何内容。 –

+0

@RichardSmith这是有道理的,一个参数不是一个位置。如果我将'location〜* ...'更改为'location =/image.php',我可以在位置块内的if语句中将$ arg_hash正则表达式吗?或者它应该是另一种方式? – Rodent85

+0

你可以使用'if',但是你不能使用'try_files'。你坚持使用'/image.php?hash ='风格的请求吗? –

您可以使用类似下面

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处理代码