首页 > 解决方案 > Nginx 与位置不匹配

问题描述

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

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

它总是回退到 location / 的默认内容。但是,我在 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;
        }

谢谢你的帮助。

标签: nginx

解决方案


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

在同一个块中使用aliasand可能会有问题try_fileslocation

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

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

locationandalias值应该都以 结尾,或者/都不以 结尾/。该^~运算符将阻止其他正则表达式location块匹配任何以/admin. 请参阅此使用注意事项if


推荐阅读