Nginx 重写位置到子文件夹

Nginx Rewrite Location to subfolders

我需要帮助来确定将字符拆分到子文件夹的最佳方法是什么?我特别需要的是将 url /file/12345.jpg 重写为 /1/2/3/4/5/12345.jpg FS 路径。 (数字不仅限于这些 - 它们可以是数字的任意组合,例如:/file/123.jpg、/file/123456789.jpg 等)

这是基本位置。

location ~ ^/file/(.+)\.(.+)$ {
   ....
}

一种可能性是描述所有变体:

location ~ ^/file/(\d)\.(.+)$ {
   alias /file//.;
}
location ~ ^/file/(\d)(\d)\.(.+)$ {
   alias /file///.;
}

等等

但它很丑而且效率不高。

/file/12af5.jpg/1/2/a/f/5/12af5.jpg:

location ~ ^/files/((\w)(\w)(\w)(\w)(\w))\.(.*) {
  rewrite "//////." break;
}

要获得更多动态功能,请考虑使用 rewrite_by_lua (custom nginx build required) or use OpenResty, 开箱即用。您还可以将请求代理到 Python/Node/Php/etc 后端服务器,以使用您选择的语言动态重定向。