我有很多静态文件,其名称遵循以下模式:
sku_(no)_1.jpg,sku_(no)_2.jpg,sku_(no)_3.jpg …
哪里(不)是6位数字。 因为有这么多的,我必须把它们放到不同的目录,并使用alias
指令redirect请求,如:
location ~* (sku_\d+(\d)(\d)(\d)_\d+)\.(jpg|png|jpeg|gif)$ { alias /path_to_directory/$4/$3/$2/$1.$5; }
现在困难的部分是,有时候,请求会带有大写字母,例如请求文件sku_101138_1.JPG
/ path_to_directory / 8/3/1 / sku_101138_1。 JPG
然而,实际的文件存储为
/ path_to_directory / 8/3/1 / sku_101138_1。 JPG
这会导致404 not found
那么如何告诉nginx在使用alias
指令时忽略大小写呢?
你可以使用map指令。
# must be defined outside of server block map $ext $ext_lower { ~*jpg jpg; ~*png png; ~*jpeg jpeg; ~*gif gif; } location ~* (sku_\d+(\d)(\d)(\d)_\d+)\.(jpg|png|jpeg|gif)$ { # set named variables set $name $4/$3/$2/$1; set $ext $5; alias /path_to_directory/$name.$ext_lower; }
在这里,我必须指出两件事情:
map
必须位于任何server
块之外,并且对于所有的nginxconfiguration都是全局的。 $ext_lower
之前定义命名variables,因为一旦我们使用它,由于使用正则expression式,它将毁掉所有位置variables( $1
, $2
,…)。 所以alias /path_to_directory/$4/$3/$2/$1.$ext_lower;
将不起作用,因为$1
– $4
将是空的。