5

Let's say I have a URL such as:

http://www.example.com/something.html?abc=one&def=two&unwanted=three

I would like to remove the URL parameter unwanted and keep the rest of the URL in tact and it should look like:

http://www.example.com/something.html?abc=one&def=two

This specific parameter can be anywhere in the URL with respect to other parameters. The redirect should work regardless.

Can this be achieved?

Hitesh
  • 330
  • 1
  • 4
  • 10
  • possible duplicate of [Remove parameters within nginx rewrite](http://stackoverflow.com/questions/9641603/remove-parameters-within-nginx-rewrite) – Justin Oct 15 '14 at 14:16
  • 1
    No, in that question, the OP asks to remove ALL query parameters from URL, as opposed to a specific query parameter. – Hitesh Oct 15 '14 at 14:20
  • Seems like this can only be done in scripts, such as lua scripts (which will require to install a lua module into the nginx). Example like: https://www.ruby-forum.com/topic/4417604 – JasonYang Oct 15 '14 at 15:45

3 Answers3

9

You can achieve that this way

if ($request_uri ~ "([^\?]*)\?(.*)unwanted=([^&]*)&?(.*)") {
    set $original_path $1;
    set $args1 $2;
    set $unwanted $3;
    set $args2 $4;
    set $args "";

    rewrite ^ "${original_path}?${args1}${args2}" permanent;
}
Milos Jovanovic
  • 306
  • 2
  • 7
5

I wanted to do something similar to this and here's the result ammended back to the context of the original question (regex is based on Milos Jovanovic's Answer)

if ($request_uri ~ "([^\?]*)\?(.*)unwanted=([^&]*)&?(.*)") {
  set $args $2$4;

  rewrite "^" $scheme://$host$uri permanent;
}

this way we only set one variable and if the updated $args is empty we dont have an unwanted ? at the end of the url as the server handles that itself

Cyber Axe
  • 176
  • 3
  • 7
0

An other way is to redirect the client.

Of course it would work only for GET or HEAD, not if request has a body (ie: POST PUT PATCH)

BTW: in the specific case of fbclid the second line in map isn't required as the param is always appended to the url


map $request_uri $redirect_fbclid {
  "~^(.*)(?:[?&]fbclid=[^&]*)$"         $1;
  "~^(.*)(?:([?&])fbclid=[^&]*)&(.*)$"  $1$2$3;
}

if ( $redirect_fbclid ) {
  return 301 $redirect_fbclid;
}

Antony Gibbs
  • 1,321
  • 14
  • 24