1

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.

gidiwe2427
  • 109
  • 1
  • 7

1 Answers1

1

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.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • Its almost working. Just a little problem: hxxps://example.com/tester.php?unwanted1=111&unwanted2=222&unwanted2=222 will be rewrited to hxxps://example.com/tester.php?unwanted1=111 So our 'unwanted param' will not get stripped if its on the first place. – gidiwe2427 Aug 05 '21 at 03:29
  • Your regular expression currently requires the unwanted parameter to be proceeded by an `&`. Try: `^(?:(?.*)&)?(?:unwanted1|unwanted2)=[^&]*(?&.*)?$` – Richard Smith Aug 05 '21 at 08:45