nginx JavaScript 模块
njs 是一个 nginx 模块,通过 JavaScript 脚本扩展了服务器的功能,支持创建自定义服务器端逻辑和 更多。
用例
- 在请求到达上游服务器之前,在 njs 中进行复杂的访问控制和安全检查
- 操作响应头
- 编写灵活的异步内容处理程序和过滤器
查看 示例 以获取更多 njs 用例。
基本 HTTP 示例
在 nginx 中使用 njs
-
安装 njs 脚本语言
-
创建一个 njs 脚本文件,例如
http.js
。查看 参考 获取 njs 属性和方法的列表。function hello(r) { r.return(200, "Hello world!"); } export default {hello};
-
在
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; } } }
还有一个独立的 命令行 工具,可以独立于 nginx 使用,用于 njs 的开发和调试。
已测试的操作系统和平台
- FreeBSD / amd64;
- Linux / x86, amd64, arm64, ppc64el;
- Solaris 11 / amd64;
- macOS / x86_64;