我正在将设置从 apache 迁移到 nginx。在此过程中,我在 .htaccess 文件中遇到了此重写规则:
RewriteRule ^/?(?:(?!one|two|three|four).?)+/?$ http://somewhere.else.com [R=301,L]
我通常很擅长正则表达式,但这远远超出了我的理解范围。首先,我甚至不知道允许使用嵌入括号。有人能给我解释一下这个正则表达式吗?如果这是 apache 独有的东西,我如何在 nginx 中复制它?
答案1
(?!one|two|three|four)
意思是“非(一或二或三或四)”。表示
?:
非捕获组(因此您不能使用 来引用它$N
,例如$1
)。总之,它几乎意味着任何其中没有“一”、“二”、“三”或“四”序列的文本。
例如:
如果此 URL/categories/category-1/hello-kitten/
符合上述规则,则将被重定向。但此 URL/categoneries/category-1/hello-kitten/
不会重定向,因为它具有顺序一其中:/categ***one***ries/category-1/hello-kitten/
答案2
以下是一些更具体、更详细的信息,希望对您有帮助:
' ^/?(?:(?!one|two|three|four).?)+/?$ http://somewhere.else.com [R=301,L]
'
' Options: case insensitive
'
' Assert position at the beginning of the string «^»
' Match the character “/” literally «/?»
' Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
' Match the regular expression below «(?:(?!one|two|three|four).?)+»
' Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
' Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!one|two|three|four)»
' Match either the regular expression below (attempting the next alternative only if this one fails) «one»
' Match the characters “one” literally «one»
' Or match regular expression number 2 below (attempting the next alternative only if this one fails) «two»
' Match the characters “two” literally «two»
' Or match regular expression number 3 below (attempting the next alternative only if this one fails) «three»
' Match the characters “three” literally «three»
' Or match regular expression number 4 below (the entire group fails if this one fails to match) «four»
' Match the characters “four” literally «four»
' Match any single character that is not a line break character «.?»
' Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
' Match the character “/” literally «/?»
' Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
' Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
' Match the characters “ http://somewhere” literally « http://somewhere»
' Match any single character that is not a line break character «.»
' Match the characters “else” literally «else»
' Match any single character that is not a line break character «.»
' Match the characters “com ” literally «com »
' Match a single character present in the list “R=301,L” «[R=301,L]»