Nginx Rewrite Convert Querystring to Path

34,259

Solution 1

If you want redirect

location ~ /somefolder/mypage.aspx {
    if ($args ~* "^myid=(\d+)&tab=overview") {
        set $mid $1;
        set $args '';
        rewrite ^.*$ /folder/$mid/overview permanent;
    }
}

Don't forget to configure /folder/$1/overview location.

Solution 2

A shorter and more correct version of Valery Viktorovsky answer.

location = /somefolder/mypage.aspx {
    if ($arg_tab != overview) { return 404; }
    if ($arg_myid !~ "^\d+$") { return 404; }
    rewrite ^ /folder/$arg_myid/overview? permanent;
}

Or, hey, it can even be shorter, if you don't need to be verifying the arguments:

rewrite ^/somefolder/mypage.aspx /folder/$arg_myid/$arg_tab? permanent;
Share:
34,259

Related videos on Youtube

YardenST
Author by

YardenST

Updated on September 18, 2022

Comments

  • YardenST
    YardenST almost 2 years

    I whould like this simple rewrite rule:

    /somefolder/mypage.aspx?myid=4343&tab=overview
    

    to be redirected to:

    /folder/4343/overview/
    

    I looked for some solutions and none actually worked..

    I tried:

    rewrite ^/somefolder/mypage.aspx?myid=(.*)&tab=overview$  /folder/$1/overview  permanent;
    

    and

    rewrite ^/somefolder/mypage\.aspx\?myid=(.*)&tab=overview$  /folder/$1/overview  permanent;
    

    What am I doing wrong? I'm getting 404

    (simpler rules works just fine..)

    Thanks

  • YardenST
    YardenST over 11 years
    Thanks, the redirect works, but without the paramater ($1)... it is blank
  • Valery Viktorovsky
    Valery Viktorovsky over 11 years
    I updated answer.
  • YardenST
    YardenST over 11 years
    wish you had posted it earlier :) it would've save me some time
  • Congmin
    Congmin over 11 years
    lol. did you have a lot of rules like that? well, better late than never! also, can i get an accept, then? :)
  • YardenST
    YardenST over 11 years
    Valery solution works bottom line :) and there could be only one answer :)
  • Congmin
    Congmin over 11 years
    meta.stackexchange.com/questions/5234/… « Make sure that besides working for you, the answer is really good practice. Sometimes after the answer gets accepted, another comes in, uncovering the fact that previous one was in fact a bad hack. » Seriously, there are not just one, but a several different problems with Valery's answer! Every line is essentially wrong, other than the curly braces!