[nginx] Fixed try_files in locations with alias and static strings.

Maxim Dounin mdounin at mdounin.ru
Sat Apr 25 05:47:52 UTC 2026


details:   http://freenginx.org/hg/nginx/rev/aad0fdcc2e33
branches:  
changeset: 9502:aad0fdcc2e33
user:      Maxim Dounin <mdounin at mdounin.ru>
date:      Sat Apr 18 01:44:24 2026 +0300
description:
Fixed try_files in locations with alias and static strings.

Previously, a configuration like:

    location /prefix/ {
        alias /foo/;
        try_files /prefix/bar =404;
    }

tried the "/foo/prefix/bar" file, unless variables were used in the argument.
Similarly,

    location /prefix/ {
        alias /foo/;
        set $fallback /prefix/bar;
        try_files ... $fallback;
    }

incorrectly redirected to "/bar" instead of "/prefix/bar" if no files
were found (and variables were used in the fallback argument).

The fix is to move alias prefix matching to a point after fallback handling,
and do it for both variables and static strings.

diffstat:

 src/http/modules/ngx_http_try_files_module.c |  22 +++++++++++-----------
 1 files changed, 11 insertions(+), 11 deletions(-)

diffs (45 lines):

diff --git a/src/http/modules/ngx_http_try_files_module.c b/src/http/modules/ngx_http_try_files_module.c
--- a/src/http/modules/ngx_http_try_files_module.c
+++ b/src/http/modules/ngx_http_try_files_module.c
@@ -174,23 +174,12 @@ ngx_http_try_files_handler(ngx_http_requ
             path.len = e.pos - path.data;
 
             *e.pos = '\0';
-
-            if (alias && alias != NGX_MAX_SIZE_T_VALUE
-                && ngx_filename_cmp(name, r->uri.data, alias) == 0)
-            {
-                ngx_memmove(name, name + alias, len - alias);
-                path.len -= alias;
-            }
         }
 
         test_dir = tf->test_dir;
 
         tf++;
 
-        ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
-                       "trying to use %s: \"%s\" \"%s\"",
-                       test_dir ? "dir" : "file", name, path.data);
-
         if (tf->lengths == NULL && tf->name.len == 0) {
 
             if (tf->code) {
@@ -213,6 +202,17 @@ ngx_http_try_files_handler(ngx_http_requ
             return NGX_DONE;
         }
 
+        if (alias && alias != NGX_MAX_SIZE_T_VALUE
+            && ngx_filename_cmp(name, r->uri.data, alias) == 0)
+        {
+            ngx_memmove(name, name + alias, len - alias);
+            path.len -= alias;
+        }
+
+        ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
+                       "trying to use %s: \"%s\" \"%s\"",
+                       test_dir ? "dir" : "file", name, path.data);
+
         ngx_memzero(&of, sizeof(ngx_open_file_info_t));
 
         of.read_ahead = clcf->read_ahead;


More information about the nginx-devel mailing list