Nginx location directive with regular expression to extract folder name and using in try_files

牧云@^-^@ 提交于 2019-12-12 18:17:00

问题


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;
}

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.

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.

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

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

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

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


回答1:


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;
}

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.



来源:https://stackoverflow.com/questions/44193158/nginx-location-directive-with-regular-expression-to-extract-folder-name-and-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!