Nginx与位置不匹配

时间:2020-05-14 09:19:02

标签: nginx

谁能告诉我为什么此ngnix配置与所有以/ admin开头的URL不匹配:

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

它总是返回到位置/的默认内容。但是,我在Nginx配置中对所有可能的URL进行了硬编码,它可以工作并且仅与硬编码的URL相匹配,例如:

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

try_files语句的最后一项是URI。 index.html上的/path/to/admin/build/index.html文件的URI为/admin/index.html

在同一aliascan be problematic中使用try_fileslocation

您可能想使用更可靠的解决方案:

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

locationalias的值都应以/结尾或都不以/结尾。 ^~运算符将阻止其他正则表达式location块与以/admin开头的任何URI匹配。关于if的使用,请参见this caution