棘手的 nginx 重定向规则与文件夹和子文件夹

Tricky nginx redirect rules with folders and subfolders

我想用nginx实现这样的301重定向:

https://www.example.com/foo1/bar1 -> https://www.example.com/foo2/bar2 
https://www.example.com/foo1/bar3 -> https://www.example.com/foo2/bar4 
https://www.example.com/foo1/whatever -> https://www.example.com/foo2/whatever 
https://www.example.com/foo1?argumet -> https://www.example.com/foo2?argument 

为了尝试完成这个我正在尝试使用:

#Redirect the longest forced links first
location ~ ^/foo1/bar1 {
    return 301 https://www.example.com/foo2/bar2;
    break;
}
location ~ ^/foo1/bar3 {
    return 301 https://www.example.com/foo2/bar4;
    break;
}
#Redirect everything else except for the matches above according to the rule
location ~ ^/foo1(?:/(.*))?$ {
    return 301 https://www.example.com/foo2/$is_args$args;
}

前3种情况都可以。但是,对于最后一种情况,我将重定向到:

https://www.example.com/foo2/?argument

而不是

https://www.example.com/foo2?argument

...这破坏了网站的逻辑。

你能帮我解决这个问题吗? 谢谢!

尝试:

location ~ ^/foo1(/.*)?$ {
    return 301 /foo2$is_args$args;
}