本文介绍了Nginx位置指令与正则表达式提取文件夹名称并在try_files中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下location指令以及try_files来实现Restfull应用程序:

I'm currently using the following location directive along with the try_files for a restfull application:

location /branches/branchx/app/api/ {
    try_files $uri $uri/ /branches/branchx/app/api/api.php$is_args$args;
}

其中branchx是我的Git分支的名称.因此,我可能有多个分支,例如:branch1branch2等.

Where branchx is the name of my Git branch. I may therefore have multiple branches such as: branch1, branch2, etc..

因此,我需要为要创建的每个分支手动创建一个指令.

And therefore I need to manually create a directive for each and every branches I will create.

为避免此问题,我希望使用正则表达式提取分支名称,并在try_files指令中使用它.因此,我将拥有一个由单个位置管理的动态系统指令负责所有分支机构.

To avoid this issue, I'm looking to use a regular expression to extract the branch name and using it in my try_files directive. So I'd have a dynamic system managed by a single location directive taking care of all branches.

到目前为止,所有在try_files中使用正则表达式的尝试都将引发405或404错误.

All attempts to use a regex so far in the try_files end up by throwing a 405 or 404 error.

我最后一次尝试(基于@Richard Smith的回答):

My last attempt (based on @Richard Smith answer):

location ~ ^(/branches/[^/]+/app/api)/ {
    try_files $uri $uri/ $1/api.php$is_args$args;
}

其中哪一个返回了405(不允许)响应,以匹配uri.

Which returned a 405 (Not Allowed) response for matching uri.

推荐答案

如果使用正则表达式location,则可以同时捕获路径.例如:

If you are using a regular expression location, you can capture the path at the same time. For example:

location ~ ^(/branches/[^/]+/app/api)/ {
    try_files $uri $uri/ $1/api.php$is_args$args;
}

重要说明:从前缀location更改为正则表达式location将更改评估顺序.正则表达式location块按顺序求值,因此/branches/branchx/app/api/api.php将匹配该location,除非放置在location ~ \.php$位置块之后.有关详细信息,请参见本文档.

Important note: Changing from a prefix location to a regular expression location will change the evaluation order. Regular expression location blocks are evaluated in order, so /branches/branchx/app/api/api.php will match this location block unless it is placed after the location ~ \.php$ location block. See this document for details.

这篇关于Nginx位置指令与正则表达式提取文件夹名称并在try_files中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 06:08