skip to Main Content

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


  1. You have a trailing slash in your regex, so it would only match www.example.com/section/?page=3/.

    Try ^/section/?page=(.*)$

    Login or Signup to reply.
  2. 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:

    location  /section/ {
        return 301 https://www.example.com/page/$arg_page;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search