aleclofabbro
aleclofabbro

Reputation: 1699

nginx perl set variables

Having this nginx rule:

  location ~ /test/ {
    set $color '?';
    set $subpath $1;
    perl test::handle;
    add_header Content-Type "text/html";
    return 200 $color;
  }

and this perl file:

package test;

use nginx;
sub handle {
    my $r = shift;
    $r->variable('color', 'blue');
    return OK;
}

1;
__END__

I would expect nginx to serve the string blue
but ? is served instead.
I tested a sub handle like this: (modifying properly the rule commenting the return)

sub handle {
    my $r = shift;
    $r->send_http_header;
    $r->print($r->variable('color'),'<br/>');
    $r->variable('color', 'blue');
    $r->print($r->variable('color'),'<br/>');
    $r->flush();
    return OK;
}

and i get expected result :

?
blue

in first case does nginx serves $color before having it being set by perl ? How to avoid this?
To clarify:
I need to set a bunch of variables in perl script, depending on request, i could trigger one perl_set for each variable i need to set, but i would like to integrate all in one function.
[EDIT]
it's actually illegal to use perl_set directive inside location block, so, perl_set is not on per-request basis.

Upvotes: 2

Views: 3064

Answers (1)

Mehran Mahmoudi
Mehran Mahmoudi

Reputation: 121

I know that this answer is very over due. but i have experimented with it now.

you were wrong on this :

it's actually illegal to use perl_set directive inside location block, so, perl_set is not on per-request basis.

actually even if you should include perl_set in http block of config file the code will be re-evaluated on every request. so if you include below config in you http block $color will be blue;

perl_set $color '
    sub {
        my $r = shift;
        return \'blue\';
    }
';

but remember perl_set in http block will be eveluated before location block so if you include set $color '?'; in your location block variable will always have ? value.

Upvotes: 2

Related Questions