Nginx Redirect - Remove a specific query parameter

2019-02-05 10:26发布

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?

2条回答
唯我独甜
2楼-- · 2019-02-05 10:31

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

查看更多
Root(大扎)
3楼-- · 2019-02-05 10:43

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;
}
查看更多
登录 后发表回答