I want to achieve a 301 redirect like this with nginx:
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
In order to try and acomplish this I am trying to use:
#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/$1$is_args$args;
}
It is all good for the first 3 situations. However, for the last situation, I am getting a redirect to:
https://www.example.com/foo2/?argument
instead of
https://www.example.com/foo2?argument
...and it breaks the logic of the site.
Can you please help me get this right? Thanks!
Try:
location ~ ^/foo1(/.*)?$ {
return 301 /foo2$1$is_args$args;
}