Referencing Query Params with Dashes in NGINX Config
I spent some time recently configuring NGINX for one of our microservices, and one of the problems I had to solve was configuring NGINX cache bypass when a specific query parameter is set. This is usually trivial to do by using the cache bypass directives, where NGINX automatically maps the value of the nocache
query parameter from the URL to the $arg_nocache
variable.
And it just works, like so:
proxy_cache_bypass $arg_nocache;
proxy_no_cache $arg_nocache;
However due to some legacy reasons, I had to support the query parameter named qa-nocache
, which contains a dash character. In this case, NGINX can’t automatically map the parameter to the $arg_qa-nocache
variable, since -
isn’t a valid character for identifiers in nginx.conf
Mapping the Parameter Manually
To solve the issue, I mapped the query parameter to a variable manually, specifying a map
block in the config file:
map $args $param_qa_nocache {
"~(^|&)qa-nocache=(?<val>[^&]+)" $val;
}
This block takes the raw query string $args
and finds the value of the qa-nocache
parameter using a regular expression. Then it puts the value of the parameter into the newly declared $param_qa_nocache
variable. If the parameter is not found in the query string, $param_qa_nocache
will get a default value of the empty string.
We can then use this new variable as a parameter for our cache bypassing directives like this:
proxy_cache_bypass $param_qa_nocache;
proxy_no_cache $param_qa_nocache;