Appearance
nginx JavaScript 模块
提示
来自deepseek解释
原文链接:https://nginx.org/en/docs/njs/index.html
njs 是一个 nginx 模块,通过 JavaScript 脚本扩展服务器的功能,支持创建自定义的服务端逻辑及更多用途。
相关链接
相关模块
进阶主题
使用场景
- 在请求到达上游服务器之前,在 njs 中实现复杂的访问控制和安全检查
- 操作响应头
- 编写灵活的异步内容处理程序与过滤器
更多 njs 使用示例,请参见 examples。
基础 HTTP 示例
要在 nginx 中使用 njs:
安装 njs 脚本语言
创建一个 njs 脚本文件,例如
http.js。有关 njs 属性和方法的完整列表,请参见参考文档。jsfunction hello(r) { r.return(200, "Hello world!"); } export default {hello};在
nginx.conf文件中,启用 ngx_http_js_module 模块,并通过 js_import 指令指定http.js脚本文件:nginxload_module modules/ngx_http_js_module.so; events {} http { # 自 0.9.1 版本起 js_engine qjs; 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