我有一些nginx变量藐视我的server_content.conf文件是否有一种方式,我们可以访问它在我的。js文件?servercontent.conf…设置$debug_log 'off';…
logging.jsIf (ngx.var.debug_log = 'on'). .做一些
使用SSI
解决这个问题的第一种方法是使用Server Side Includes模块。
下面是一个简单的例子:
- nginx配置片段:
set $debug_log on;
location / {
ssi on;
ssi_types application/javascript;
...
}
logging.js
示例
var logging = '<!--# echo var="debug_log" -->';
console.log("Debug status detected via SSI substitution is", logging);
阅读模块文档,找出所有可用的特性。
为了安全起见,如果只有一个JS文件,你想从nginx接收一些数据,为这个文件声明一个单独的位置(这也会加速所有其他JS内容的服务),例如,如果它的URI是/js/logging.js
:
location / {
... # default location
}
location = /js/logging.js {
# do not cache this file at the client side
add_header Cache-Control "no-cache, no-store, must-revalidate";
ssi on;
ssi_types application/javascript;
}
使用AJAX端点
解决这个问题的第二种方法是用nginx配置定义一个AJAX端点:location = /getdebug {
default_type application/json;
return 200 '{"logging":"$debug_log"}';
}
现在$debug_log
nginx值可以使用AJAX调用从浏览器端JavaScript代码获得:
const xhr = new XMLHttpRequest();
xhr.open('GET', '/getdebug');
xhr.responseType = 'json';
xhr.onload = function() {
if (this.status == 200) {
console.log('Debug status detected via AJAX request is', this.response.logging);
}
};
更新1
原来整个问题是关于njs而不是浏览器端JavaScript。理论上,这可以通过使用responseBuffer
甚至responseText
子请求对象属性的子请求API来实现。您可以查看设置nginx var作为异步操作的结果示例,特别是这个,使用某种更简单的纯文本端点:
location = /getdebug {
default_type text/plain;
return 200 $debug_log;
}
不幸的是,我不熟悉njs(我使用lua-nginx模块用于类似的目的),不知道是否有更直接的方法来做到这一点(这可能存在)。
另外,如果你想在njs中使用Node模块,请务必阅读使用Node模块与njs文档章节。
更新2
所有nginx变量(根据每个请求进行评估)都可以通过r.variables{}
HTTP请求对象属性在njs代码中使用,例如
if (r.variables.debug_log == 'on') {
... do something
}