使用Nginx为基于字符串形式的URL提供图像

时间:2017-03-02 22:13:10

标签: nginx

我想通过Nginx提供上传的图片,因此Express-App可以专注于其他任务。在这种情况下,通常的别名方法似乎还不够。

Harddrive上的文件/图像:

图像被重命名并存储在随机字符串下。这就是files-folder在硬盘上的外观:

/srv/expressap/uploads/files/images

33134ijnas9d8.jpg
81j917asdlkas.png
ja982p1031la0.png
...

请求网址获取图片

htto://www.project.com/files/images/33134ijnas9d8/puppy.jpg
htto://www.project.com/files/images/81j917asdlkas/mittens.png
htto://www.project.com/files/images/ja982p1031la0/snuggles.png

问题

这显然不起作用,因为'puppy.jpg'不是图像'33134ijnas9d8.jpg'的实际文件名

location /files/images {
   alias /srv/expressap/uploads/files/images
}

位置部分如何在给定网址下提供实际图像?

如何 1)从网址获取id-string?

2)根据id-string服务图像?

1 个答案:

答案 0 :(得分:3)

You need to use regexp for this, Nginx supports them.

location ~* ^/files/images/(\w+)/.+\.(jpg|png|gif)$ {
   alias /srv/expressap/uploads/files/images/$1.$2;
}

~* - regexp case-insensitive modifier

(\w+) - any word-like sequence without spaces

$1, $2 - references to the matching groups in brackets

Details about using regexps with alias here.

So, you mostly need to extract some parts of the $uri by means of a regexp and pass them to the alias directive. You may test your regexp here, though I didn't test it with Nginx, implementation may differ.