I inherited a legacy site and for SEO reasons wish to redirect old parameter links to the new api. Like so:
www.example.com/section/?page=3 => www.example.com/page/3
Here is my attempt at a regex redirect:
location ~ ^/section/?page=(.*)/$ {
return 301 https://www.example.com/page/$1;
}
I’ve used this pattern countless times without issue but after hours of poking I still can’t get the redirect working. Clearly Nginx treats parameters differently.
Any tips?
2
Answers
You have a trailing slash in your regex, so it would only match
www.example.com/section/?page=3/
.Try
^/section/?page=(.*)$
You don’t need regex here, it would add unnecessary processing overhead anyway.
Nginx captures url parameters already. you can use the
$args
variable for all the parameters, or individual ones are prefixed$arg_
, so assuming all your urls match this format you can just use a location block like this: