OliFausN
OliFausN

Reputation: 13

Substitute query string parameter based on query string params in nginx

Preset:

We need to substitute a query parameter t=http://endpoint/:df01:/:df02:/:df03:/004.jpg with other query parameters ...?:df01:=1&:df02:=13&:df03:=9 we are passing in the request.

Result:

Redirect the request to http://endpoint/1/13/9/004.jpg.

By now we have a rule in our nginx.conf working well by executing the following rule :

    if ($args ~ "^rt=rt0010_01&.*&:df\d+:=(\d+)&:df\d+:=(\d+)&:df\d+:=(\d+)&t=(https?:\/\/.*)\/Newsletter\/.*\/.*\/.*\/(.*)") {
        set $location $4;
        set $params $2/$1/$3/$5;
        rewrite . $location/Newsletter/$params? redirect;
    }

Our problem is that we cannot dynamically change the arguments in the t= path like t=http://endpoint/:df01:/:df03:/:df02:/004.jpg, because the params argument is set "hardcoded" to $2/$1/$3/$5.

So my question is, can I build some kind of rewrite rule which parses the :dfxx: params in the t= variable and then substitute it with the other params suppied in the request or do I have to include some module extension which perhaps can do the job? (Btw, we also have to solve the hardcoded /Newsletter in the rewrite , it is yet present in the url supplied by the t=... param).

I was asked to add an example containing a full request and a corresponding response:

REQUEST:

http://nginx-srv.com/rd/?rt=rt0010_01&cid=609&:df01:=609&:df26:=02&:df08:=1&t=http://my.domain/Newsletter/:df26:/:df01:/:df08:/008.jpg

RESPONSE:

http://my.domain/Newsletter/02/609/1/008.jpg

I hope this is sufficient.

Upvotes: 0

Views: 650

Answers (1)

Gerard H. Pille
Gerard H. Pille

Reputation: 2578

With the following rules you can shift the df parameters, and the endpoint is variable.

      if ($args ~ "(.*&?):(df\d\d):=(\d+)(&?.*/):\2:(/.*)" ) {
        set $args  $1$4$3$5;
      }
      if ($args ~ "(.*&?):(df\d\d):=(\d+)(&?.*/):\2:(/.*)" ) {
        set $args  $1$4$3$5;
      }
      if ($args ~ "(.*&?):(df\d\d):=(\d+)(&?.*/):\2:(/.*)" ) {
        set $args  $1$4$3$5;
      }
      if ( $args
           ~ "&?t=(https?:\/\/[^/]*/)([A-Za-z]*)(\/.*\/.*\/.*\/)([^&]*)&?" ) {
        set $rscheme $1;
        set $endpoint $2;
        set $arguments $3;
        set $image $4;
      }
      rewrite . $rscheme$endpoint$arguments$image? redirect;
      return 301;

An URL with the parameters

:df01:=1&:df02:=13&:df03:=9&t=http://my.domain/Newsletter/:df01:/:df02:/:df03:/004.jpg

gets rewritten to

http://my.domain/Newsletter/1/13/9/004.jpg

With parameters

:df02:=13&:df01:=1&:df03:=9&t=http://your.domain/Letternews/:df02:/:df03:/:df01:/lookatme.jpg

it gets redirected to

http://your.domain/Letternews/13/9/1/lookatme.jpg

Upvotes: 2

Related Questions