rewrite详解

rewrite

语法:rewrite regex replacement flag;,如:

rewrite ^/test/(.*\.jpg)$ /change/$1 break;

[root@nginx ~]# cd /usr/local/nginx/html/
[root@nginx html]# mkdir test
#上传图片test.jpg

修改配置文件

 server {
        listen       80;
  #      server_name  192.168.163.128;

        charset utf-8;

        access_log  logs/host.access.log  main;

        location / {
            root   /www;
            index  index.html index.htm index.php;
        }
        #增加如下内容
         location /test {
               root html;
               index index.html;
        }

重启服务,访问网页

将test目录改为change
[root@nginx html]# vim /usr/local/nginx/conf/nginx.conf
[root@nginx html]# mv test/ change/   
[root@nginx html]# ll
总用量 1260
-rw-r--r--. 1 root root    537 10月 18 08:42 50x.html
-rw-r--r--. 1 root root    612 10月 18 08:42 index.html
drwxr-xr-x. 2 root root     22 10月 24 16:20 change

修改配置文件

         location /haha {
               root html;
               index index.html;
               rewrite ^/test/(.*\.jpg)$ /change/$1 break;    #增加这一行
        }

重启服务,重新请求

可看到虽然没有test目录,但仍可访问到文本文件,URL重写成功
我们也可以让url做多次跳转,最多可以跳20次
二次跳转实例
实验思路
客户端发出的请求改变后的URL(test)———>改变后的URL(change )——>https://blog.csdn.net/qq_43094192
修改配置文件

location /test {
               root html;
               index index.html;
               rewrite ^/test/(.*\.jpg)$ /change/$1 last;       #将break换成last
        }     
        #增加如下内容,再次跳转到博客链接结束
         location /change {
               rewrite  ^/change/(.*\.jpg)$ https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=965139422,648637599&fm=27&gp=0.jpg break;
        }
重启nginx

posted @ 2019-06-10 18:14  道鸿  阅读(963)  评论(0编辑  收藏  举报