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?


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

// Works as expected
// location: https://renthall.se/produkt/lagerhall

// But...

curl http://mydomain.com/category-1/product-a-v
// 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