在默认情况下,nginx的rewrite是不支持UTF8匹配的

如果要让^/(..)$匹配到2个汉字字符,得开启nginx对utf8字符的正则支持,准确点说是开启nginx使用的pcre库的对utf8字符的支持。

需要使用pcre7.9以上的版本才支持中文rewrite,另外,编译PCRE时一定要开启utf8的支持,即使用--enable-utf8参数 ,检查系统的PCRE版本和是否支持UTF8编码可以使用。
pcretest -C

PCRE version 8.13 2011-08-16
Compiled with
UTF-8 support
Unicode properties support
Newline sequence is LF
R matches all Unicode newlines
Internal link size = 2
POSIX malloc threshold = 10
Default match limit = 10000000
Default recursion depth limit = 10000000
Match recursion uses stack

显示UTF-8就是支持UTF8编码

如果nginx调用的PCRE为7.9以下的版本,
使用 rewrite “(*UTF8)^/(..)$” /2个字符文章.html break; 这种形式的重写,在执行nginx -t检查时会出现如下的错误提示:
[emerg]: pcre_compile() failed: (*VERB) not recognized in “(*UTF8)^、……
如果Nginx调用的是7.9以上版本的PCRE,但是PCRE安装时没打开UTF8的支持开关,则会出现如下的错误提示:

nginx: [emerg] pcre_compile() failed: this version of PCRE is not compiled with PCRE_UTF8 support in “(*UTF8)^/…

解决办法是安装最新版本的的PCRE,并打开UTF8支持,方法如下(以当前8.13版的PCRE为例):wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.13.tar.gztar zxvf pcre-8.13.tar.gzcd pcre-8.13./configure --enable-utf8 --enable-unicode-propertiesmakemake install
然后重新编译安装Nginx。 Nginx默认会打开rewrite模块,并会自动查找系统上已经安装了的PCRE。 如果Nginx查找不到已经安装在系统上的PCRE, 或者系统上有多个PCRE, nginx调用了不支持UTF8的、或低版本的PCRE时(我遇到了后一种情况,并花费了很长的时间解决这个问题,这也是我为什么写这篇总结文章在这里给大家分享的原因。。。),可以在编译安装Nginx时指定PCRE源文件。例如:
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.13.tar.gztar zxvf pcre-8.13.tar.gzwget http://nginx.org/download/nginx-1.0.8.tar.gztar zxvf nginx-1.0.8.tar.gzcd nginx-1.0.8./configure --with-pcre=../pcre-8.13
注意,如果接着直接make && make install的话, PCRE因为没有启用UTF8, nginx将不能支持UTF8重写, 所以在这一种,我动了一点小手脚:打开./objs/Makefile 文件,找到以下段落:
../pcre-8.13/Makefile: objs/Makefilecd ../pcre-8.13 && if [ -f Makefile ]; then $(MAKE) distclean; fi && CC="$(CC)" CFLAGS="-O2 -fomit-frame-pointer -pipe " ./configure --disable-shared 在–disable-shared后加上 –enable-utf8和 –enable-unicode-properties参数, 即变成:../pcre-8.13/Makefile: objs/Makefilecd ../pcre-8.13 && if [ -f Makefile ]; then $(MAKE) distclean; fi && CC="$(CC)" CFLAGS="-O2 -fomit-frame-pointer -pipe " ./configure --disable-shared --enable-utf8 --enable-unicode-properties