Nginx rewrite rules and match only beginning of string

A nice little gotcha. Often when you write Nginx rules, you forget that it matches everything in the string. Imagine if you want this redirect /product-a -> /category-1/product-a


Add ^ to match the beginning of the string.

^/product-a -> /category-1/product-a


//Rewrite rule (without ^) 

// /product-a

// TO
// /category-1/product-a

curl -v

// Works as expected, matches product-a
// location:

// But...

// Error too many redirects
// Matches product-a at the end of the string

Nginx rewrite rules matches all the strings and if it finds on of the rule matches: /product-a -> /category-1/product-a

Adding a slash could work, but usually you don’t have Nginx configured to add an ending slash:

/product-a -> /category-1/product-a