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

Please consider the following URLs.


Among the four, I need to redirect one as follow:

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;


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;

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

Leave a Comment