如何通过获取第一段来重写随机生成的nginx路径?

问题描述 投票:0回答:1

我有一个prestashop实例,该实例生成一个用于管理员访问的随机URL。唯一的规则是路径以“ admin”开头。

以下规则很好用,但是用手工对其进行了硬编码:

location /admin6908ewwh6/ {
    if (!-e $request_filename) {
        rewrite ^/.*$ /admin6908ewwh6/index.php last;
    }
}

我试图将其重写为:

location ^(/admin.*?)(\w+)/ {
    if (!-e $request_filename) {
        rewrite ^/.*$ $1/index.php last;
    }
}

但是这不起作用,我不知道为什么,因为根据这个正则表达式匹配器(https://www.regextester.com/102896),当我将^(/admin.*?)(\w+)正则表达式放在测试字符串/admin6908ewwh6/index.php/sell/catalog/products/new?_token=_JC1fQPwgvwnhZTWyeGVTy4nET350GC4Aro888TuzDA&上时,它只是抓住了我需要的内容。

有人可以解释一下为什么这两个位置块不相等吗?

nginx mod-rewrite url-rewriting nginx-location
1个回答
0
投票

问题是$1。数值捕获由要评估的最后一个正则表达式分配,在这种情况下,该正则表达式为rewrite语句(尽管正则表达式中没有括号)。

一种解决方案是在rewrite语句中进行捕获,例如:

location /admin {
    if (!-e $request_filename) {
        rewrite ^(/admin[^/]+)/ $1/index.php last;
    }
}

或不带if块:

location /admin {
    try_files $uri $uri/ @admin;
}
location @admin {
    rewrite ^(/admin[^/]+)/ $1/index.php last;
}
© www.soinside.com 2019 - 2024. All rights reserved.