Nginx、PCRE和中文URL(UTF8编码)rewrite路径重写匹配问题

最近遇到了使用Nginx 重写中文UTF8编码路径的问题。 才发现默认状况下Nginx的rewrite是不支持UTF8匹配的。 好比:html

rewrite ^/(..)$ /2个字符文章.html break; #用2个点
能够匹配到 /ab 或 /51, 但 /汉字 是匹配不到的。 我测试了一下, 要匹配两个字的 /汉字 路径, 得用nginx

rewrite ^/(……)$ /2个汉字文章.html break; #要用六个点测试

若是要让 ^/(..)$ 匹配到2个汉字字符,得开启Nginx对UTF8字符的正则支持, 准确点说是开启Nginx使用的PCRE库的对UTF8字符的支持。由于Nginx的rewrite模块是调用PCRE来处理正则的。 若是PCRE没有问题,Nginx支持UTF8编码的重写样式是:this

rewrite "(*UTF8)^/(..)$" /2个字符文章.html break;
#注意(*UTF8)前缀和引号的加入。
编码

由于PCRE只有7.9以上的版本才支持这个(*UTF8)开头,因此系统上的PCRE必定要使用7.9以上的版本。 另外,编译PCRE时必定要开启UTF8的支持。 即便用(–enable-utf8)参数。 检查系统的PCRE版本和是否支持UTF8编码可使用
pcretest -C
命令。执行后会显示以下的报告:
url

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 stackspa

显示“UTF-8 support”就是支持UTF8编码了。日志

若是Nginx调用的PCRE为7.9如下的版本,使用 rewrite “(*UTF8)^/(..)$” /2个字符文章.html break; 这种形式的重写,在执行nginx -t检查时会出现以下的错误提示:code

[emerg]: pcre_compile() failed: (*VERB) not recognized in “(*UTF8)^、……htm

若是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.gz
tar zxvf pcre-8.13.tar.gz
cd pcre-8.13
./configure --enable-utf8 --enable-unicode-properties
make
make 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.gz
tar zxvf pcre-8.13.tar.gz
wget http://nginx.org/download/nginx-1.0.8.tar.gz
tar zxvf nginx-1.0.8.tar.gz
cd nginx-1.0.8
./configure 
--with-pcre=../pcre-8.13

注意,若是接着直接make && make install的话, PCRE由于没有启用UTF8, nginx将不能支持UTF8重写, 因此在这一种,我动了一点小手脚:打开./objs/Makefile 文件,找到如下段落:

../pcre-8.13/Makefile: objs/Makefile
cd ../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/Makefile
cd ../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

而后再make, make install。 最后关闭nginx并重启nginx(这里不能用nginx -s reload)。这样nginx就支持中文UTF8编码的url重写了。

转载请注明: 转自船长日志, 本文连接地址: http://www.cslog.cn/Content/nginx-pcre-utf8-rewrite/

相关文章
相关标签/搜索