njs 脚本语言

njs scripting language - njs 脚本语言

https://nginx.org/en/docs/njs/index.html

njs is a subset of the JavaScript language that allows extending nginx functionality. njs is created in compliance with ECMAScript 5.1 (strict mode) with some ECMAScript 6 and later extensions. The compliance is still evolving.

​ njs 是 JavaScript 语言的一个子集,它允许扩展 nginx 的功能。njs 是按照 ECMAScript 5.1(严格模式)创建的,带有一些 ECMAScript 6 和后续的扩展。遵循程度仍在不断地发展中

使用案例 - Use cases

  • Complex access control and security checks in njs before a request reaches an upstream server
  • 在 njs 中进行复杂的访问控制和安全性检查,以防止请求达到上游服务器之前
  • Manipulating response headers
  • 操纵响应头
  • Writing flexible asynchronous content handlers and filters
  • 编写灵活的异步内容处理程序和过滤器

See examples and blog posts for more njs use cases.

​ 有关更多 njs 使用案例,请参见 示例博客文章

基本的 HTTP 示例 - Basic HTTP Example

To use njs in nginx:

​ 要在 nginx 中使用 njs:

  • install njs scripting language

  • 安装 njs 脚本语言

  • create an njs script file, for example, http.js. See Reference for the list of njs properties and methods.

  • 创建一个 njs 脚本文件,例如 http.js。请参阅 参考 获取 njs 属性和方法的列表。

    function hello(r) {
     r.return(200, "Hello world!");
    }
    
    export default {hello};
    
  • in the nginx.conf file, enable ngx_http_js_module module and specify the js_import directive with the http.js script file:

  • nginx.conf 文件中,启用 ngx_http_js_module 模块,并使用 http.js 脚本文件指定 js_import 指令:

    load_module modules/ngx_http_js_module.so;
    
    events {}
    
    http {
     js_import http.js;
    
     server {
         listen 8000;
    
         location / {
             js_content http.hello;
         }
     }
    }
    

There is also a standalone command line utility that can be used independently of nginx for njs development and debugging.

​ 还有一个独立的 命令行 实用程序,可用于独立于 nginx 进行 njs 的开发和调试。

Tested OS and platforms

​ 经过测试的操作系统和平台

  • FreeBSD / amd64;
  • Linux / x86, amd64, arm64, ppc64el;
  • Solaris 11 / amd64;
  • macOS / x86_64;

在 nginx.conf 2018 上的演示 - Presentation at nginx.conf 2018

最后修改 August 16, 2023: 更新 (c140bba)