Nginx NJS module

49 Views Asked by At

I want to initialize the variable in the Nginx setting file using the njs module. Here is my sample code.

<< default.conf >>
server {
listen 80 default_server;

js_path "/etc/nginx/njs";
js_import testnjs.js;

location / {
root /usr/share/nginx/html;
index index.html index.htm;
}

location /jstest {
js_var $testVariable;
js_content testnjs.sub;
return 200 $testVariable;
}


<< testnjs.js >>
function sub(r){
r.variables['testVariable'] = "CONTENT";
}

If I send a http request to /jstest, I don't get any results. I want the testVariable variable to be initialized. How do I change the code?

I want the testVariable variable to be initialized.

1

There are 1 best solutions below

0
On

You can return from the js function itself:

function sub(r) { 
   r.variables['testVariable'] = "CONTENT"; 
   r.return(200, r.variables['testVariable']); 
} 

And in case you want to print the variable in the log for whatever reason, use the following:

log_format main '$time_local $remote_addr "$request" "$http_referer"  
$status $body_bytes_sent $http_content_length "$upstream_addr" 
"$http_user_agent" "$http_x_forwarded_for" - "$testVariable";

access_log /var/log/nginx/access.log main; 

server { 

  set $testVariable '';
  ...

  location /jstest {
      js_content testnjs.sub;
  }

}