Score:1

Stop Nginx rewrites breaking all pages following location block

gb flag

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.

Richard Smith avatar
jp flag
To match only `/brands/exampleA/`, use `location = /brands/exampleA/`
zigojacko avatar
gb flag
Ah amazing, thanks @RichardSmith adding an = exactly fixed the issue. Add as answer if you want me to accept as solution :)
Score:1
jp flag

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.

zigojacko avatar
gb flag
Worked perfectly, thanks. Cheers for the doc ref as well as I did try searching but wasn't sure what to search for really so did not come across this but that's ideal
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.