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

Solution

Add ^ to match the beginning of the string.

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

Why?

//Rewrite rule (without ^) 

// FROM
// /product-a

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

curl http://mydomain.com/product-a -v

// Works as expected, matches product-a
// location: https://mydomain.com/product-a

// But...

// Error too many redirects
// Matches product-a at the end of the string
curl http://mydomain.com/category-1/product-a


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