'Nginx redirect using part of last_path_component

I am redirecting from domain1 to domain2 based on what's present in the URI, but I need to pass to domain2 only the first part of the last path component.

The main entry point to be redirected would be:

https://www.domain1.com/us/type-a-products/**9011-HWD-bolts-new**

new end point:

https://www.domain2.com/us-us/type-a-products/**9011**

So I need to consider only the first part of the last past component before the first hypen (basically the product code).

The redirect is easy to do:

 if ($request_uri ~* "([^/]*$)" ) {
   set  $last_path_component  $1;
 }
 location ~ /us/type-a-products/(.*) {
     return 301 https://www.domain2.com/us-us/type-a-products/$1;
 }

But how can I consider only the first part of the last path component (tried different regexs but I only managed to extract the word after the last hyphen).

Any help would be much appreciated!



Solution 1:[1]

A good place to do this is in a map. It happens early in the nginx cycle and will not short circuit the flow of your config by introducing regex locations.

outside of the server config

map $uri $redirect_id_uri {
    ~^/us/type-a-products/\*\*(?<id>\d+)-.*\*\*$ https://www.domain2.com/us/type-a-products/**$id**;
}

inside server config

if ($redirect_id_uri) {
    return 301 $redirect_id_uri;
}

Solution 2:[2]

You can use

([^/-]+)[^/]*$

See the regex demo. Details:

  • ([^/-]+) - Group 1: any one or more chars other than / and -
  • [^/]* - any zero or more chars other than /
  • $ - end of string.

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 Cole Tierney
Solution 2 Wiktor Stribiżew