Nginx not matching the location

Can anyone tell me why is this ngnix config doesn't match all URL that starts with /admin :

    location /admin {
        alias {{path_to_static_page}}/admin/build/;
        try_files $uri $uri/ /index.html;
    }

It always fall back to the default content of location / . However, I hardcoded all the possible URL in the Nginx config, it works and only matches the hard coded URL, something like :

        location /admin {
            alias {{path_to_static_page}}/admin/build/;
            try_files $uri $uri/ /index.html;
        }

        location /admin/news/ {
            alias {{path_to_static_page}}/admin/build/;
            try_files $uri $uri/ /index.html;
        }

        location /admin/another-url/ {
            alias {{path_to_static_page}}/admin/build/;
            try_files $uri $uri/ /index.html;
        }

Thanks for your help.

Upvotes: 1

Views: 1587

Answers (1)

Richard Smith
Richard Smith

Reputation: 49672

The final term of the try_files statement is a URI. The URI of the index.html file at /path/to/admin/build/index.html is /admin/index.html.

Using alias and try_files in the same location block can be problematic.

You may want to use a more reliable solution:

location ^~ /admin {
    alias /path/to/admin/build;
    if (!-e $request_filename) { rewrite ^ /admin/index.html last; }
}

The location and alias values should both end with / or neither end with /. The ^~ operator will prevent other regular expression location blocks from matching any URI that begins with /admin. See this caution on the use of if.

Upvotes: 1

Related Questions