nginx - 配置 nginx 重写所有路径上的哈希值

标签 nginx url-rewriting nginx-location

我首先使用 nginx 作为静态文件服务器,并尝试重写所有 uri(如果它们包含哈希值以指向模拟目录)。

举个例子可能会更清楚

假设用户请求页面网址如下:

/api/some/path/to/ecbac7cb-21ca-3d22-98ed-4d063f138d0b/some/other/path/02167621-5c01-45c5-98ba-eb3ba1bf4b2a/list

/api/some/other/path/to/ecbac7cb-21ca-3d22-98ed-4d063f138d0b

我想首先尝试获取文件,但后备会是这样的

/api/some/path/to/__any_hash__/some/other/path/__any_hash__/list.json

/api/some/other/path/to/__any_hash__.json

这是我尝试过的配置...但显然,它不起作用。

server {
 ...
 location /api {
  try_files $uri $uri/index.html $uri.html $uri.json $uri.xml @rewrites;
 }

 location @rewrites {
  rewrite /([0-9\-a-f]{36})/ __any_hash__ break;
  try_files $uri.xml $uri.json @backend;
 }

有人有想法吗?

最佳答案

您的位置@rewrites可能应如下所示:

location @rewrites {
    rewrite "^(.*)/[0-9\-a-f]{36}(/.*)$" $1/__any_hash__$2 last;
    return 404;
}

$1$2 捕获要替换的哈希之前和之后的 URI 片段。 last 导致替换后重新尝试 location/api。该过程将循环进行,直到完成所有替换为止。仅当完全替换的 URI 找不到文件时才会调用 return 404

关于nginx - 配置 nginx 重写所有路径上的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35141171/

相关文章:

php - 对css,js和静态文件的更改未反射(reflect)在nginx docker容器上

Nginx 无法在 Windows 10 上创建目录,错误为 : nginx: CreateFile(). ..failed

.htaccess - 如何重写 .htaccess 中菜单项的 URL

file - 重写 WWW 和文件扩展名?

php - Apache 重写规则适用于本地主机但不适用于服务器

Nginx 位置匹配

php - ECS 挂载卷到 nginx 容器

ruby - "Incompatible library version"on nokogiri

php - 当文件大小大于 2mb 时,Laravel 文件上传失败

php - 如何减少 TTFB(到第一个字节的时间)响应?