[PATCH 7 of 7] Fixed try_files to clear r->valid_unparsed_uri

Maxim Dounin mdounin at mdounin.ru
Fri Apr 17 22:45:42 UTC 2026


# HG changeset patch
# User Maxim Dounin <mdounin at mdounin.ru>
# Date 1776465873 -10800
#      Sat Apr 18 01:44:33 2026 +0300
# Node ID 5158f263a08ebf7711392744296a1c12261924e3
# Parent  75c4159a5ac363763054a2ba49a66f36c45f9bb8
Fixed try_files to clear r->valid_unparsed_uri.

Most notably, with this change any URI changes made by try_files are
visible with proxy_pass without URI, such as in the following
configuration:

    location / {
        try_files $uri $uri.html =404;
        proxy_pass http://u;
    }

Previously, such URI changes were only visible if URI was previously
changed by a rewrite or an internal redirect.

To minimize compatibility issues, this is only done when the new URI
is not equal to the original one.  That is, a configuration like
this will work as before, preserving the original URI as sent by the
client:

    location / {
        try_files $uri =404;
        proxy_pass http://u;
    }

Note that URI checking uses ngx_strncmp() rather than ngx_filename_cmp()
to properly reflect case-only changes on case-insensitive systems as well.

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
@@ -251,12 +251,13 @@ ngx_http_try_files_handler(ngx_http_requ
         path.len -= root;
         path.data += root;
 
+        name = r->uri.data;
+        len = r->uri.len;
+
         if (!alias) {
             r->uri = path;
 
         } else {
-            name = r->uri.data;
-
             r->uri.len = alias + path.len;
             r->uri.data = ngx_pnalloc(r->pool, r->uri.len);
             if (r->uri.data == NULL) {
@@ -283,6 +284,18 @@ ngx_http_try_files_handler(ngx_http_requ
                    != 0)
             {
                 r->valid_location = 0;
+                r->valid_unparsed_uri = 0;
+            }
+        }
+
+        if (r->valid_unparsed_uri) {
+
+            /* clear r->valid_unparsed_uri if URI was changed */
+
+            if (r->uri.len != len
+                || ngx_strncmp(r->uri.data, name, len) != 0)
+            {
+                r->valid_unparsed_uri = 0;
             }
         }
 



More information about the nginx-devel mailing list