带有正则表达式的 Nginx 位置指令提取文件夹名称并在 try_files 中使用
Nginx location directive with regular expression to extract folder name and using in try_files
我目前正在将以下位置指令与 try_files 一起用于 restfull 应用程序:
location /branches/branchx/app/api/ {
try_files $uri $uri/ /branches/branchx/app/api/api.php$is_args$args;
}
其中 branchx
是我的 Git 分支的名称。因此,我可能有多个分支,例如:branch1
、branch2
等..
因此我需要为我将创建的每个分支手动创建一个指令。
为了避免这个问题,我正在寻找 使用正则表达式来提取分支名称并在我的 try_files 指令中使用它。 所以我会有一个由单个位置指令管理的动态系统,负责所有分支。
到目前为止,所有在 try_files 中使用正则表达式的尝试都以抛出 405 或 404 错误告终。
我最后一次尝试(基于@Richard Smith 的回答):
location ~ ^(/branches/[^/]+/app/api)/ {
try_files $uri $uri/ /api.php$is_args$args;
}
它为匹配的 uri 返回了 405(不允许)响应。
如果你使用的是正则表达式location
,你可以同时捕获路径。例如:
location ~ ^(/branches/[^/]+/app/api)/ {
try_files $uri $uri/ /api.php$is_args$args;
}
重要说明:从前缀 location
更改为正则表达式 location
将更改求值顺序。正则表达式 location
块按顺序计算,因此 /branches/branchx/app/api/api.php
将匹配此 location
块 除非 它被放置在 location ~ \.php$
位置之后堵塞。有关详细信息,请参阅 this document。
我目前正在将以下位置指令与 try_files 一起用于 restfull 应用程序:
location /branches/branchx/app/api/ {
try_files $uri $uri/ /branches/branchx/app/api/api.php$is_args$args;
}
其中 branchx
是我的 Git 分支的名称。因此,我可能有多个分支,例如:branch1
、branch2
等..
因此我需要为我将创建的每个分支手动创建一个指令。
为了避免这个问题,我正在寻找 使用正则表达式来提取分支名称并在我的 try_files 指令中使用它。 所以我会有一个由单个位置指令管理的动态系统,负责所有分支。
到目前为止,所有在 try_files 中使用正则表达式的尝试都以抛出 405 或 404 错误告终。
我最后一次尝试(基于@Richard Smith 的回答):
location ~ ^(/branches/[^/]+/app/api)/ {
try_files $uri $uri/ /api.php$is_args$args;
}
它为匹配的 uri 返回了 405(不允许)响应。
如果你使用的是正则表达式location
,你可以同时捕获路径。例如:
location ~ ^(/branches/[^/]+/app/api)/ {
try_files $uri $uri/ /api.php$is_args$args;
}
重要说明:从前缀 location
更改为正则表达式 location
将更改求值顺序。正则表达式 location
块按顺序计算,因此 /branches/branchx/app/api/api.php
将匹配此 location
块 除非 它被放置在 location ~ \.php$
位置之后堵塞。有关详细信息,请参阅 this document。