我可以在 try_files nginx 指令中使用两个命名位置吗?

May I use two named locations within try_files nginx directive?

我想使用类似的东西:

location @a1 {
    ...
}

location @a2 {
    ...
}

location /path {
    try_files @a1 $uri @a2
}

在@a1 位置可以继续尝试 $uri / @a2 吗?

如果是这样,nginx 将如何处理?

你不能,因为 try_files 只会将其 last 参数视为命名位置 — 在你的示例中,nginx 将查找名为 @a1 并忽略 location @a1 块。

try_files docs对此并没有特别明确,只是提到“最后一个参数也可以指向一个命名位置”。

This answer shows a workaround that uses error_page,这对您来说可能是一种有用的方法(取决于您想通过进入 @a1 来做什么)。

More on try_files here.

我找到了 this solution:

location /static/ {
    try_files $uri @static_svr1;
}
location @static_svr1{
    proxy_pass http://192.168.1.11$uri;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @static_svr2;
}

location @static_svr2{
    proxy_pass http://192.168.1.12$uri;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @static_svr3;
}

location @static_svr3{
    proxy_pass http://192.168.1.13$uri;
}

此示例的工作方式如下:

try_files $uri @static_svr1 @static_svr2 @static_svr3