'Remove args if request_uri begins with specific strings/regex (with some exceptions) - Nginx

I want to redirect (301) several locations if they have query params at same locations without query params, but with some exceptions.

For example, I want these locations behaviour:

  • /bob/marley -> not redirect
  • /bob/marley?query=string -> redirect to /bob/marley
  • /bob/marley/cat?name=dude -> redirect to /bob/marley/cat
  • /bob/marley/dog?name=jim -> redirect to /bob/marley/dog
  • /bob/marley/search?query=string -> not redirect

How can I do this if it would be dozens of these rules. Maybe organize it at separate file with map directive or something? Can anyone explain, please?



Solution 1:[1]

I suppose the answer for the example above would be the following:

http section:

map $request_uri $request_uri_path {
  "~^(?P<path>\/bob\/marley\/?(?:(?!\?|search).)*)(\?.*)$"  $path;
}

server section:

if ($request_uri_path) {
    return 301 $scheme://$http_host$request_uri_path;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1