官网:Server names
翻译部分: Regular expressions names
开始!
The regular expressions used by nginx are compatible with those used by the Perl programming language (PCRE).
nginx用的正则表达式和那些被PCRE用的正则表达式是可共用的。
To use a regular expression, the server name must start with the tilde character:
为了用正则表达式,server_name的参数必须以~开头。
server_name ~^www\d+\.example\.net$;
可以看到,~和参数之间不需要加空格。
otherwise it will be treated as an exact name, or if the expression contains an asterisk, as a wildcard name (and most likely as an invalid one).
否则它将会被视为确切的名称,或者如果表达式包含星号,它会被视为通配符名称。
Do not forget to set “
^
” and “$
” anchors.
不要忘记设置^和$锚点。
They are not required syntactically, but logically.
它们不是语法上需要的,而是语法上需要的。
Also note that domain name dots should be escaped with a backslash.
同时也要记得域名点要用反斜杠转义 ,例如: \.
A regular expression containing the characters “
{
” and “}
” should be quoted:
包含{和}的正则表达式应该被""包围,如下:
server_name "~^(?<name>\w\d{1,3}+)\.example\.net$";
otherwise nginx will fail to start and display the error message:
否则,nginx会启动失败并展示错误信息,错误信息如下:
directive "server_name" is not terminated by ";" in ...
A named regular expression capture can be used later as a variable:
在正则表达式中?<>包围的名字(如下的domain)可以稍后在后面作为一个变量来使用。
server { server_name ~^(www\.)?(?<domain>.+)$; location / { root /sites/$domain; } }
The PCRE library supports named captures using the following syntax:
PCRE库支持使用以下语法的命名捕获:
?<
name
>Perl 5.10 compatible syntax, supported since PCRE-7.0
Perl5.10兼容语法,从PCRE-7.0开始支持。
?'
name
'Perl 5.10 compatible syntax, supported since PCRE-7.0
Perl5.10兼容语法,从PCRE-7.0开始支持。
?P<
name
>Python compatible syntax, supported since PCRE-4.0
Python兼容语法,从PCRE-4.0开始支持。
If nginx fails to start and displays the error message:
如果nginx启动失败并展示一下错误信息:
pcre_compile() failed: unrecognized character after (?< in ...
this means that the PCRE library is old and the syntax “
?P<
” should be tried instead.name
>
这意味着PCRE库是旧版的,应该用?P<name>试试。
The captures can also be used in digital form:
捕获也可以用数字形式使用:
server { server_name ~^(www\.)?(.+)$; location / { root /sites/$2; } }
$2表示正则表达式匹配到的第2个参数 ,
如果匹配到www.example.com,那$2就是example.com。
~^(www\.)?(.+)$解释:
1.~表示这是一个正则表达式
2.^表示以后面匹配的内容开头
3.(www\.)表示匹配www.,结合^就是匹配以www.开头的字符串
4.?表示前面的子表达式匹配最多1次,结合上面是:只能匹配www.0次或1次
5.(.+)表示匹配单个字符至少1次,.表示匹配除换行符 \n 之外的任何单字符,+表示匹配1次或多次
6.$表示以前面匹配的字符串结尾
However, such usage should be limited to simple cases (like the above), since the digital references can easily be overwritten.
然而,这种用法应该只限于简单的情况,因为数字引用很容易被覆盖。