一、rewrite是什么
1 a location is searched based on a request URI;
译:location是用来匹配uri的,当匹配时,执行该location里的指令,否则继续向下匹配剩余location,直至结束
2 the directives of this module specified inside the found location are executed sequentially;
译:location里的指令顺序执行
3 the loop is repeated if a request URI was rewritten, but not more than 10 times.
译:uri被重写次数不超过10次
rewrite regex replacement[flag];
rewrite是实现url重写的指令,根据正则regex匹配,并跳转到replacement,flag用来控制跳转规则,取值包括break, last, redirect, permanent四种。
二、正则及flag标记说明
符号 | 说明 |
---|---|
^ | 指定匹配字符串开始 |
$ | 指定匹配字符串结束 |
. | 任意非空字符 |
+ | 量词,匹配1次或多次 |
* | 匹配0次或多次 |
? | 量词,匹配0次或1次 |
() | 作为一个整体匹配 |
[] | 匹配括号中的任意一项 |
标记 | 说明 |
---|---|
break | 本条规则匹配完成后终止,不在匹配任何规则 |
last | 本条规则匹配完成后,从server开始发起新一轮的匹配,最多10次 |
redirect | 返回302临时重定向 |
permanent | 返回301永久重定向 |
三、常用rewrite匹配规则说明
1 301 跳转
rewrite ^/(.*) http://sohu.com/$1 permanent;
2 302 跳转
rewrite ^/(.*) http://sohu.com/$1 redirect;
3 url重写
location / {
rewrite "/category\?id=(\d+)$" /category/show/$1 break;
}
参考文档
1 nginx_http_rewrite_module