Nginx正则表达式和可选的反向引用

时间:2013-09-16 06:03:36

标签: regex nginx pcre backreference

我想选择匹配字符串(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匹配(?:asdf)来剥离mydomain.com/pencil-.html <{1}}

1 个答案:

答案 0 :(得分:0)

我制定了一个解决方案,以便我只使用后面的引用$ 1和$ 3忽略$ 2,无论它是匹配还是null。

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