浅聊关于 nginx 的 rewrite

rewrite用法

rewrite用法

Syntax:	rewrite regex replacement [flag];
Context: server, location, if

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

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

rewrite标识符主要包含四种:

- 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 withhttp://”, “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命令,比如下面例子

rewrite '^/([0-9]{4})/\d+/\d+/(.*)$' '/$1/$2' last;

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

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

shikanon wechat
欢迎您扫一扫,订阅我滴↑↑↑的微信公众号!