Nginx – Stop Rewrites from Breaking Pages Following Location Block

nginxngx-http-rewrite-module

I'm having to rewrite URLs in nginx.conf that contain particular query parameters;

As an example:-

location /brands/exampleA {

    if ($arg_cat = "9") {
        return 301 /page/brand-filter;
    }

    if ($arg_cat = "38") {
        return 301 /page/category/brand-filter;
    }

}

These URL rewrites would then rewrite example.com/brands/exampleA/?cat=9 to example.com/page/brand-filter and example.com/brands/exampleA/?cat=38 to example.com/page/category/brand-filter.

And these work perfectly, but the problem is that they break every other child page of the location block so for example, the following pages would all not load with an Nginx error:-

example.com/brands/exampleA/range1
example.com/brands/exampleA/range2
example.com/brands/exampleA/range3
example.com/brands/exampleA/range4

So is there something I can add to the location statement to stop anything applying to anything after exampleA – these rewrites should ONLY match ?cat= query parameters.

Best Answer

Your configuration currently uses a prefix location, which means that it is considered when the requested URI begins with the value /brands/exampleA.

To restrict the match to only one URI, use the exact match syntax:

location = /brands/exampleA/ { ... }

See this document for details.