perlnginxmod-perl

How to Set return of perl function in request header using nginx


Could anyone help me with nginx with a perl module? I have already managed to create a function in Perl using the ubi8/nginx-124 image but I am not able to set the result of the function in the header.

0

Having this in nginx configuration file:

http {
   perl_modules /opt/app-root/etc/nginx/nginx-perl/;
   perl_require module1.pm;
   perl_set $test module1::handler; #it is not calling the function here, it is only called in the location block
}
location = /perl {
    perl module1::handler; #I've already tried with and without this line
    add_header X-My-Header $test; #I tried adding the header this way and from within the code with $r.But both without success
}

and this perl file:

package module1;;

use nginx;
sub handler {
    my $r = shift;
    my $foo = 'foo';

    $r->send_http_header("text/html");
    $r->header_out("WWW-Authenticate" => $foo);

    $r->print("<h3>SUCCESS:</h3>");
    return $foo;
}
1;

Solution

  • This is the correct way:

    package module1;
    
    use lib '/opt/app-root/etc/nginx/nginx-perl/';
    
    use strict;
    use nginx;
    
    sub handler {
       my $r = shift;
       $r->header_out("X-Custom-Header", "CUSTOM_VALUE"); #This line has to be placed before of send_http_header
       $r->send_http_header("text/html");
       $r->print("Hello, world!");
       return OK;
    }
    

    1;

    And the configuration file must to be:

    http {
      perl_modules /opt/app-root/etc/nginx/nginx-perl/;
      perl_require module1.pm;
    }
    location = /perl {
      perl module1::handler;
    }
    

    Another way could be:

    http {
      perl_modules /opt/app-root/etc/nginx/nginx-perl/;
      perl_require module1.pm;
      perl_set $foo module1::handler;
    }
    location = /perl {
      proxy_pass http://aplha.beta.com;
      proxy_set_header  "X-Custom-Header" $foo;
    }
    
    sub handler {
       return 'CUSTOM_VALUE';
    }