【问题标题】:How to rewrite randomly generated nginx path by taking the first segment?如何通过取第一段来重写随机生成的 nginx 路径?
【发布时间】:2020-04-28 18:50:25
【问题描述】:

我有一个 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】:

    问题是$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;
    }
    

    或者没有rewrite 声明:

    location ~ ^(/admin[^/]+)/ {
        try_files $uri $uri/ $1/index.php$is_args$args;
    }
    

    确保最后一个位置块位于处理 .php URI 的块之下。

    【讨论】:

      猜你喜欢
      • 2016-05-10
      • 1970-01-01
      • 2020-01-15
      • 2018-04-03
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多