Remove parameters within nginx rewrite

拈花ヽ惹草 提交于 2019-11-27 16:01:35

问题


I'm rewriting URLs in nginx after a relaunch. In the old site I had query parameters in the URL to filter stuff e.g.

http://www.example.com/mypage.php?type=4

The new page doesn't have these kind of parameters. I want to remove them and rewrite the URLs to the main page, so that I get:

http://www.example.com/mypage/

My rewrite rule in nginx is:

location ^~ /mypage.php {
    rewrite ^/mypage.php$ http://www.example.com/mypage permanent;
}

But with this rule the parameter is still appended. I thought the $ would stop nginx from processing further values... any ideas? All other questions deal with how to add parameters - I just want to remove mine :)


回答1:


Had a similar problem, after a lot of searching the answer presented itself in the rewrite docs.

If you specify a ? at the end of a rewrite then Nginx will drop the original $args (arguments)

So for your example, this would do the trick:

location ^~ /mypage.php {
    rewrite ^/mypage.php$ http://www.example.com/mypage? permanent;
}



回答2:


To drop a parameter from a URL, in this case coupon=xxx:

if ($query_string ~ "^(.*)coupon=(.*)$") {
    rewrite ^(.*)$ $uri? permanent;
}

Note that this will drop all parameters if the statement matches. $uri is the original request without parameters.




回答3:


Try setting the $args variable to empty inside the location.

set $args '';



回答4:


If you want to remove a specified parameter from url,

#  in location directive: 
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;
}

then visit your_site.com/a=1&unwanted=2&c=3

step1. server gives an 302 response, indicating the url is match.

step2. client re-send a request with the new url ( with the parameter removed)



来源:https://stackoverflow.com/questions/9641603/remove-parameters-within-nginx-rewrite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!