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.

4
  • Have you tried using two if...set blocks, one for each unwanted parameter? Commented Aug 3, 2021 at 6:38
  • Does this question answer your question? stackoverflow.com/questions/26384776/… Commented Aug 3, 2021 at 7:10
  • @RichardSmith No. It will not work if I have the same string multiple times example.com/?unwanted2=aaa&unwanted2=aaa it will just remove the first unwanted2 Commented Aug 3, 2021 at 7:22
  • @patrick Its using rewrite which will not modify the $args Commented Aug 3, 2021 at 7:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Your regular expression currently requires the unwanted parameter to be proceeded by an &. Try: ^(?:(?<prefix>.*)&)?(?:unwanted1|unwanted2)=[^&]*(?<suffix>&.*)?$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.