nginx rewrite操作示例

$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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值