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!
2
Answers
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.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
inside server config