上一篇我们已经会安装nginx了,但是还不支持重定向。
要支持重定向得在nginx编译时安装pcre库。
pcre全称是Perl Compatible Regular Expressions,是来处理正则表达式的。
我们去官网下载:
http://www.pcre.org/
我在linux直接下载并解压:
cd /home/xiaofei/src
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.38.tar.bz2
tar -xjvf pcre-8.38.tar.bz2
pcre不需要按装,只需要将nginx联编。
cd /home/xiaofei/src/nginx-1.11.3
../configure –prefix=/usr/local/nginx –with-pcre=/home/xiaofei/src/pcre-8.38
make -j8 && make install
可能会报如下错:
src/core/ngx_regex.h:24: error: expected specifier-qualifier-list before ‘pcre’
make1: * [objs/src/core/nginx.o] Error 1
make1: Leaving directory `/home/xiaofei/src/nginx-1.11.3’
是因为pcre需要依赖 pcre-devel,这是一个系统相关库,安装很简单:
yum install pcre-devel
再次编译nginx
cd /home/xiaofei/src/nginx-1.11.3
../configure –prefix=/usr/local/nginx –with-pcre=/home/xiaofei/src/pcre-8.38
make -j8 && make install
安装成功
启用nginx
/usr/local/nginx/sbin/nginx
ps aux | grep nginx
启用成功。
浏览器访问:
我们现在可以用rewrite功能了:
我们修改nginx配置:
cd /usr/local/nginx/conf
vi nginx.conf
修改以下配置:
server {
listen 80;
server_name localhost;location /baidu{ rewrite ^/baidu/(.*)/(.*) http://$1.baidu.com/$2 break; }
}
我们在浏览器上输入:
跳转到
跳转成功。
在研究rewrite之前先看看匹配:
- 表示精确匹配
- ~ 表示区分大小写正则
- ~* 表示不区分大小写正则
- ^~ 匹配到后不再向下搜索
再来看看rewrite:
上面例子中的rewrite语句:
rewrite ^/baidu/(.)/(.) http://$1.baidu.com/$2 break;
归纳就是:
rewrite regex replacement flag;
regex为正则语句, replacement为目标。
flag官网是这样介绍的:
last
stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;
break
stops processing the current set of ngx_http_rewrite_module directives as with the break directive;
redirect
returns a temporary redirect with the 302 code; used if a replacement string does not start with “http://” or “https://”;
permanent
returns a permanent redirect with the 301 code.
实际意义redirect与permanent一个返回302,一个返回301。
last, break表示停止后面的匹配。
比如,一个location里可以有多个rewrite:
location ~ /baidu/{
- rewrite ^/baidu/music/(.*) http://music.baidu.com/$1 break;
- rewrite ^/baidu/news/(.*) http://news.baidu.com/$1 break;
- rewrite ^/baidu/(.*) http://www.baidu.com/$1 break;
}
在浏览器输入
http://192.168.8.6/baidu/news/
都能跳转到相应页面: