nginx 如何使用rewrite

上一篇我们已经会安装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;
   }

}

我们在浏览器上输入:

http://192.168.8.6/baidu/music/

跳转到
这里写图片描述

跳转成功。
在研究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/

都能跳转到相应页面:
这里写图片描述


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值