阅读 86

nginx rewrite url重写, if实现负载均衡 ,nginx反向代理配置

 

  rewrite   (url 重写)

语法:rewrite regex replacement flag;,如:

 

将url 开头为/imgs 下所有的以.jpg结尾的文件路径全部转成 /images下所有.jpg结尾的文件

rewrite ^/imgs/(.*\.jpg)$ /images/$1 break;

 

 

在nginx网页访问目录下创建一个目录,在里面放入一张图片

[root@localhost imgs]# pwd
/usr/local/nginx/html/imgs
[root@localhost imgs]# ls
dog.jpg

 

在网页上访问

 

 

 

 

 

将原图片存放位置修改名字

[root@localhost html]# mv imgs images
[root@localhost html]# ls
50x.html  images  index.html

 

 

 

 

 

 

将rewrite机制写入配置文件中

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
        location /imgs {
            rewrite ^/imgs/(.*\.jpg)$ /images/$1 break;
        }
        

//测试一下配置文件语法有无问题
[root@localhost html]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
// 重载配置文件
[root@localhost html]# nginx -s reload

 

我并没有改变网页访问的路径,但是他还是能访问到图片

 

 

 

 

 

还有一种写法

rewrite ^/images/(.*\.jpg)$   www.baidu.com break;

 

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
        location /imgs {
            rewrite ^/imgs/(.*\.jpg)$ http://www.baidu.com break;
        }

[root@localhost html]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost html]# nginx -s reload

 

 

 

他直接就跳转到了百度

 

 

 

 

 

 

 

 

 

常见的flag

 

flag作用
last 基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个
一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理
而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break 中止Rewrite,不再继续匹配
一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求,
且不再会被当前location内的任何rewrite规则所检查
redirect 以临时重定向的HTTP状态302返回新的URL
permanent 以永久重定向的HTTP状态301返回新的URL

 

原文:https://www.cnblogs.com/meijianbiao/p/14838310.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐