【问题标题】:Nginx Regex and optional backreferenceNginx 正则表达式和可选的反向引用
【发布时间】:2013-09-16 06:03:36
【问题描述】:

我想选择性地匹配一个字符串 (asdf) 并将其从重写中删除。

location ~ /somefolder {
    rewrite ^/somefolder(.*)(?:asdf)?(.*html)$ http://example.com$1$2 permanent;
}

因此,这会将请求的 url 重写为根域,并删除任何出现 asdf 的 url(如果存在)。

下面地址mydomain.com/somefolder/pencil.html改写为mydomain.com/pencil.html

2013/09/16 09:52:24 [notice] 16866#0: *1 "^/somefolder(.*)(?:asdf)?(.*html)$" matches "/somefolder/pencil.html", client: 10.0.0.2, server: mydomain.com, request: "GET /somefolder/pencil.html HTTP/1.1", host: "mydomain.com"
2013/09/16 09:52:24 [notice] 16866#0: *1 rewritten redirect: "http://mydomain.com/pencil.html", client: 10.0.0.2, server: mydomain.com, request: "GET /somefolder/pencil.html HTTP/1.1", host: "mydomain.com"

这里mydomain.com/somefolder/pencil-asdf.html被重写为mydomain.com/pencil-asdf.html

2013/09/16 09:52:31 [notice] 16866#0: *1 "^/somefolder(.*)(?:asdf)?(.*html)$" matches "/somefolder/pencil-asdf.html", client: 10.0.0.2, server: mydomain.com, request: "GET /somefolder/pencil-asdf.html HTTP/1.1", host: "mydomain.com"
2013/09/16 09:52:31 [notice] 16866#0: *1 rewritten redirect: "http://mydomain.com/pencil-asdf.html", client: 10.0.0.2, server: mydomain.com, request: "GET /somefolder/pencil-asdf.html HTTP/1.1", host: "mydomain.com"

不应该使用(?:asdf) 匹配产生mydomain.com/pencil-.html 来剥离asdf

【问题讨论】:

  • 您应该为您的问题添加一个答案并接受它 - 如果他们有同样的问题,这将使人们更容易找到解决方案。

标签: regex nginx pcre backreference


【解决方案1】:

我制定了一个解决方案,因此我只使用后引用 $1 和 $3 忽略 $2 是否匹配或为空。

rewrite ^/somefolder(.*)(asdf)(.*html)$ http://example.com$1$3 permanent;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 2010-11-28
    相关资源
    最近更新 更多