$uri进行正则匹配,进行rewrite操作。
1,情景需求
访问下面两个URL时
http://a.b.com/20231105db704ee0d243fc237c182bb81e87bd0e_origin.jpg
http://a.b.com/image/2023/11/05/20231105db704ee0d243fc237c182bb81e87bd0e_origin.jpg
转换为
http://a.b.com/mnt/img/image/2023/11/05/20231105db704ee0d243fc237c182bb81e87bd0e_origin.jpg
2,nginx rewrite指令
http://a.b.com/20231105db704ee0d243fc237c182bb81e87bd0e_origin.jpg的转换规则:
注意这里正则匹配表达式用双引号括起来,否则会报错。
if ($uri ~* "^/[0-9]{8}.+$") {
rewrite "^/([0-9]{4})(\d{2})(\d{2})(.*)$" https://$host/mnt/img/image/$1/$2/$3/$1$2$3$4 last;
}
http://a.b.com/image/2023/11/05/20231105db704ee0d243fc237c182bb81e87bd0e_origin.jpg的转换规则:
if ( $uri !~* ^\/mnt\/.* ) {
rewrite ^(.*)$ https://$host/mnt/img$1 last;
}
3,这里为什么使用flag:last ?
因为还有一个location /mnt/取匹配处理rewrite后的URL,所以此处使用last,继续向下匹配location进行处理。而用break的话,会直接返回URL。
last
stops processing the current set of
ngx_http_rewrite_module
directives and starts a search for a new location matching the changed URI;
break
stops processing the current set of
ngx_http_rewrite_module
directives as with the break directive;