Nginx Rewrite

一、基本规则

1.Location分类

location可以分为三类:

     location =    精准匹配
     location       一般匹配
     location  ~   正则匹配

备注:
~ :   区分大小写
~*:不区分大小写
!~:   区分大小写不匹配
!~* : 不区分大小写不匹配
^~ :   普通字符匹配,使用前缀匹配。匹配成功,不在进行匹配规则
=   : 精准匹配

案例分析:

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
                root /var/www/html/aaa;
                index index.html aaa.html;
        }

        location = /index.html {
                root /var/www/html/bbb;
                index index.html;
        }

        location ~ /INDEX.html {
                root /var/www/html;
                index indec.html INDEX.html;
        }

[root@localhost ~]# cd /usr/local/nginx/
[root@localhost html]# mkdir aaa
[root@localhost html]# mkdir bbb
[root@localhost html]# mkdir ccc

[root@localhost html]# echo "abc">/aaa.html
[root@localhost html]# echo "bbb">/index.html
[root@localhost html]# echo "ccc">/INDEX.html
[root@localhost html]# systemctl start nginx

2.Location 优先级

=  优先级最高,匹配成功,不再进行匹配其他
^~  匹配成功,不再进行匹配其他
~和~* 正则表达式,优先级次之
/  通用匹配,任何请求都可以匹配

总结:
(location  =)>  (location ^ ~)  >  ( location ~)  >  ( location ~*)  >  ( location )  >  ( location  / )

二、示例分析

(1)基于域名跳转

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
 location / {
        root   html;
        index  index.html index.htm;

        if ($host = 'www.benet.com') 
          {
          rewrite ^/(.*)$ http://www.accp.com/$1 permanent; 
          }

备注:

$host = 'www.benet.com'  判断获取到得请求URL是否为www.benet.com   
=号两边有空格
permanent:返回 301 永久重定向,浏览器地址栏会显示跳转后的 URL 地址,爬虫更新 url,没有则返回302。

^/(.*)$

^  指的是以任何字符或字符串开始的域名都会匹配上

/  指得是url后跟的/,比如www.benet.com/index.html

.*  匹配任意多个字符,注意这里的(),括号里的内容会用后面的$1调用

$   结尾

(2)基于客户端IP访问跳转
(3)基于旧域名跳转到新域名
(4)基于参数匹配跳转
(5)基于php文件跳转
(6)基于url请求跳转

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值