【问题标题】:nginx rewrite regex with multiple backreferencesnginx 用多个反向引用重写正则表达式
【发布时间】:2020-07-16 12:20:36
【问题描述】:

我是 Nginx 的新手,正在尝试为我的 Nginx 虚拟主机设置重写规则。

/{firstname}-{lastname}.php 被重写为/Individual.php?firstname={firstname}&lastname={lastname}

/{firstname}-{lastname}-Info.php?Id=123 被重写为/Individual-Info.php?Id={id}

这就是幸福的情况。有时,可能还有一个中间名,例如

{firstname}-{middle}-{lastname}.php 改写为Individual.php?firstname={firstname}&middle={middle}&lastname={lastname}

/{firstname}-{middle}-{lastname}-Info.php?Id=123&otherparam={otherparam} 被重写为/Individual-Info.php?Id={id}&otherparam={otherparam}

有时,可能只有姓氏

{lasname}.php 改写为Individual.php?lastname={lastname}

我已阅读 rewrite 模块上的文档,但我想我只是在为正确的正则表达式苦苦挣扎,所以这可能更像是一个正则表达式问题,但我们将不胜感激。

【问题讨论】:

    标签: regex nginx url-rewriting


    【解决方案1】:

    您需要对重写进行排序,以便更具体的匹配发生在不太具体的匹配之前。先做-Info,然后三个名字,然后两个名字,然后一个名字。

    重写是模棱两可的,并且存在重定向循环的风险,尤其是对于Mr Individual。您可能应该将 rewrite 语句放在 现有 location ~ \.php$ 块中并使用 break 后缀。详情请见this document

    例如:

    location ~ \.php$ {
        rewrite -Info\.php$ /Individual-Info.php break;
        rewrite ^/(.*)-(.*)-(.*)\.php$ /Individual.php?firstname=$1&middle=$2&lastname=$3 break;        
        rewrite ^/(.*)-(.*)\.php$ /Individual.php?firstname=$1&lastname=$2 break;        
        rewrite ^/(.*)\.php$ /Individual.php?lastname=$1 break;        
        ...
    }
    

    针对您的评论,您可以使用 try_files 和命名为 location 的方式仅重写尚不存在的 .php URI。

    例如:

    location ~ \.php$ {
        try_files $uri @rewrite;
        ...
    }
    location @rewrite {
        rewrite -Info\.php$ /Individual-Info.php last;
        rewrite ^/(.*)-(.*)-(.*)\.php$ /Individual.php?firstname=$1&middle=$2&lastname=$3 last;        
        rewrite ^/(.*)-(.*)\.php$ /Individual.php?firstname=$1&lastname=$2 last;        
        rewrite ^/(.*)\.php$ /Individual.php?lastname=$1 last;        
        return 404;
    }
    

    请注意,您需要使用rewrite...last 而不是rewrite...breaktry_files 语句在您的现有 location ~ \.php$ 块中添加(或修改)。

    【讨论】:

    • 谢谢,我试试看,这些规则还会转发 URL 中的任何查询字符串吗?
    • rewrite 的默认行为是附加任何现有的查询字符串除非替换值以?结尾
    • 有没有办法只在文件不存在时才执行这些规则? @理查德史密斯
    • 感谢您的及时回复,我试过了,但它似乎改变了 URL...所以如果我在 URL 中有Someone-Info.php,那么 URL 在之后变为 Individual-Info.php这种变化......这是预期的吗?
    • 我的错,忽略我最后的评论......它没有改变 URL
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多