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


curl -v

// Works as expected
// location:

// But...

// Error too many redirects

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 works, but usually, you don’t have Nginx configured to add an ending slash:

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