nginx的使用技巧

1、重写(permanent)

说明:返回永久重定向状态码301

场景:https://test.com/t/index.html 转发到 https://www.baidu.com/

location = /t/index.html {
   rewrite /t/index.html  https://www.baidu.com/ permanent;
}

2、 重写(break)

说明:将url重写成新的地址,不是转发请求到新的location上去执行。

场景1:将 https://test.com/  转发到 https://test.com/admin

执行原理:直接将 /  替换成 /admin ,组成 https://test.com/admin 转发到服务器上。

location / {
   rewrite /  /admin/ break;
   expries off;
}

场景2:将 https://test.com/t/admin  转发到 https://test.com/web/t/admin

执行原理:$1 表示 /t/ 后面 (.*) 匹配到的任意字符 admin,将  https://test.com/t/$1 重写成  https://test.com/web/t/$1

location ~ ^/t/(.*)$ {
   rewrite ^/t/(.*)$  /web/t/$1 break;
   expries off;
}

3、匹配扩展名

场景:匹配以 /t 开头和 html 结尾的请求,例如: https://test.com/t/index.html?a=1

location ~ ^/t/(.*)\.html(.*)$ {   
   expries off;
}
 

4、静态资源配置

场景:nginx存放静态资源,使用 root 指定静态资源路径,例如:当访问 https://test.com/res/report.html?type=about 时,到 /opt/app/nginx/static/res 目录中找到静态资源 about.html

location = /res/report.html {   
   if ($arg_type != ""){
       rewrite /res/report.html /res/$arg_type.html break;  
   }   
   root /opt/app/nginx/static/;
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值