前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >浅聊关于 nginx 的 rewrite

浅聊关于 nginx 的 rewrite

作者头像
机械视角
发布2019-10-23 11:24:06
4480
发布2019-10-23 11:24:06
举报
文章被收录于专栏:Tensorbytes

rewrite用法

rewrite用法

代码语言:javascript
复制
Syntax:	rewrite regex replacement [flag];
Context:	server, location, if

rewrite的主要放在serverlocation或者if中。

语法: rewrite 正则表达式 替换内容 [标识符]

rewrite标识符主要包含四种:

代码语言:javascript
复制
- last
stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;
完成该rewrite规则的执行后,停止处理后续rewrite指令集;然后查找匹配改变后URI的新location;
- break
stops processing the current set of ngx_http_rewrite_module directives as with the break directive;
完成该rewrite规则的执行后,停止处理后续rewrite指令集,并不再重新查找;但是当前location内剩余非rewrite语句和location外的的非rewrite语句可以执行;
- redirect
returns a temporary redirect with the 302 code; used if a replacement string does not start with “http://”, “https://”, or “$scheme”;
返回302临时重定向,地址栏会显示跳转后的地址;
- permanent
returns a permanent redirect with the 301 code.
返回301永久重定向,地址栏会显示跳转后的地址;即表示如果客户端不清理浏览器缓存,那么返回的结果将永久保存在客户端浏览器中了。

1)last一般写在server和if中,而break一般使用在location中; 2)last不终止重写后的url匹配,即新的url会再从server走一遍匹配流程,而break终止重写后的匹配; 3)break和last都能组织继续执行后面的rewrite指令。

正则表达式和变量 替换内容$1$2表示前面匹配的第一个括号和第二个括号的内容,类似于Python的re模块的findall命令,比如下面例子

代码语言:javascript
复制
rewrite '^/([0-9]{4})/\d+/\d+/(.*)$' '/$1/$2' last;

$1表示([0-9]{4})匹配所得到的值; $2表示(.*)匹配所得到的值;

^表示以此为开头的完全匹配 $表示以此为结尾的完全匹配

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-02-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • rewrite用法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档