0

I'm running a web application through nginx and I need to remove part of the URL (?debug), whenever it may come up, for example:

From https://example.com/web?debug#menu=accounts

https://example.com/web?debug#menu=orders

To https://example.com/web#menu=accounts

https://example.com/web#menu=orders

My nginx configuration file had the following location block:

    location / {
            proxy_pass      http://example.com;
    }

I've looked online on ways to accomplish this, but nothing works. I've tried the following, but the url is passed as is, no changes:

    location ^~ \?debug# {
           if ($request_uri ~* "\?debug#(.*)") {
                    rewrite ^\?debug(.*)$ $1 break;
                    proxy_pass  http://example.com/$1;
           }
    }

    location / {
            proxy_pass      http://example.com;
    }

Any help would be greatly appreciated.

DaFresh
  • 1
  • 3
  • `?debug` is the query string. It is not part of the normalised URI used to match `location` and `rewrite` commands. Do you want to remove the query string, or only query strings that contains the word `debug`? – Richard Smith Apr 17 '21 at 10:28
  • Thanks for responding. I want to remove any query string that has the word debug only. i.e. https://example.com/web?debug#menu=orders must be changed to https://example.com/web#menu=orders but https://example.com/web?debug=files#menu=orders can be allowed to go through as is. I hope that clarifies it. – DaFresh Apr 17 '21 at 19:06
  • You could try: `if ($args = "debug") { rewrite ^(.*)$ $1? last; }` – Richard Smith Apr 18 '21 at 10:43
  • @RichardSmith Tried it, it's still going through with no change. Based on your previous answer re "?debug" being a query string, I did some more digging and found this code 'if ($request_uri ~ "([^\?]*)\?(.*)debug([^&]*)&?(.*)") { set $args $2$4; rewrite "^" $scheme://$host$uri permanent; }' but that removes all instances of ?debug it finds. I want something that only removes ?debug if there are no values being passed. – DaFresh Apr 18 '21 at 21:52

1 Answers1

0

I found a solution to my problem. Here's the code.

    location / {

            set $test 0;

            if ($request_uri ~ "([^\?]*)\?(.*)debug([^&]*)&?(.*)") {
                    set $test 1;
            }

            if ($request_uri ~ "([^\?]*)\?(.*)debug=files([^&]*)&?(.*)") {
                    set $test 0;
            }

            if ($test = 1) {
                    set $args $2$4;
                    rewrite "^" $scheme://$host$uri;
            }

            proxy_pass      http://example.com;
    }

Further help from the answers at these links:

Nginx Redirect - Remove a specific query parameter from URL

How can I use an "or" operator in an nginx "if" statement?

Dharman
  • 30,962
  • 25
  • 85
  • 135
DaFresh
  • 1
  • 3