nginx URL rewriting regex when URL contains a specific word but not other

Please consider the following URLs.

  1. https://products.example.com/family/child
  2. https://products.example.com/products/family/child
  3. https://products.example.com/family/children
  4. https://products.example.com/products/family/children

Among the four, I need to redirect one as follow: https://products.example.com/family/children

Which means that I want to redirect the URLs that do not contain the word /products/ and /children. If the URL does not contain the word /products/ but contain /child at the end, I need to replace the /child with /children.

UPDATE 1: I have 2 problems as below.

  1. Identify the URL that are to be substituted.
  2. Modify the identified URL as required.

I can identify the URL with this regex but not able to substitute.

Update 2: I think I found a way to identify: ^(?!.*\/products(?:\/))(?:(.*)\/|$)?(?:child)$ and substitute: $1/children

Next problem is: the regex works with option /m only. Can this be modified to work without it as:

rewrite ^(?!.*\/products(?:\/))(?:(.*)\/|$)?(?:child)$ $1/children permanent;

Answer

Something like this should work for what you’ve said above, however your question isn’t as precise as it could be and this might not be exactly what you want.

The = means exact match. Remove it and I think you get a substring match. You’ll can read the documentation for details.

location = /family/child {
  return 301 http://www.example.com/family/children;
}

Attribution
Source : Link , Question Author : Prorata , Answer Author : Tim

Leave a Comment