I want to strip url params before send it to proxy_pass
For visitor request url: => https://example.com/?wanted1=aaa&unwanted1=bbb&unwanted2=ccc&wanted2=ddd
Then it strip all the unwanted params to: => https://example.com/?wanted1=aaa&wanted2=ddd
My current way is like this:
if ($args ~ ^(.*)&(?:unwanted1|unwanted2)=[^&]*(&.*)?$ ) {
set $args $1$2;
}
But It only remove 1 param and never do recursion. How to solve this? I want to modify the $args.
If you want recursion, you can use a rewrite...last from within a location block. Nginx will only tolerate a small number of recursions (possibly ten iterations) before generating an internal server error.
For example:
location / {
if ($args ~ ^(?<prefix>.*)&(?:unwanted1|unwanted2)=[^&]*(?<suffix>&.*)?$ ) {
rewrite ^ $uri?$prefix$suffix? last;
}
...
}
Note that you need to use named captures as the numbered captures are reset when the rewrite statement is evaluated.
Note that rewrite requires a trailing ? to prevent the existing arguments being appended to the rewritten URI. See this document for details.