From f5c97428a39a68dc0f028d06b4fc8cb82054a7df Mon Sep 17 00:00:00 2001 From: xking Date: Mon, 21 Jul 2025 21:38:30 +0800 Subject: [PATCH] uodate njs --- nginx启用njs动态修改请求.md | 164 ++++++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 nginx启用njs动态修改请求.md diff --git a/nginx启用njs动态修改请求.md b/nginx启用njs动态修改请求.md new file mode 100644 index 0000000..6aed3bc --- /dev/null +++ b/nginx启用njs动态修改请求.md @@ -0,0 +1,164 @@ +### nginx 使用njs模块动态修改请求 + + + +##### 安装编译环境 + +```bash + #GCC + apt install -y build-essential + + #安装正则库 + apt install -y libpcre3 libpcre3-dev + + #安装zlib库 + apt install -y zlib1g-dev + + #openssl + apt install -y openssl libssl-dev + +``` + + + +##### 下载源码 + +``` + +# 创建源码目录 +mkdir -p ~/build && cd ~/build + +# 下载最新稳定版 Nginx +wget https://nginx.org/download/nginx-1.24.0.tar.gz +tar -zxvf nginx-1.24.0.tar.gz + +# 下载 njs 模块 +wget https://github.com/nginx/njs/archive/refs/tags/0.7.11.tar.gz -O njs-0.7.11.tar.gz +tar -zxvf njs-0.7.11.tar.gz + +``` + + + + + +##### 编译 +这里采用最小化 默认配置编译 + +``` +cd ~/build/nginx-1.24.0 +``` + +``` +./configure \ + --with-http_ssl_module \ + --with-http_v2_module \ + --with-http_realip_module \ + --with-http_gzip_static_module \ + --add-module=../njs-0.7.11/nginx + +``` +``` +make && make install +``` + + +##### 配置 + +编辑conf/nginx.conf +``` + + +worker_processes 1; +events { + + worker_connections 1024; +} + + +http { + + include mime.types; + default_type application/octet-stream; + + sendfile on; + + keepalive_timeout 65; + + include /usr/local/nginx/conf.d/*.conf; + include /usr/local/nginx/sites-enabled/*; +} + +``` + + 创建子配置目录 + +``` +mkdir /usr/local/nginx/{conf.d,sites-enabled} + + +``` +编辑子配置 + +``` + +js_import /usr/local/nginx/test.js; + +server { + listen 80; + location / { + root html; + index index.html index.htm; + } + + location /njs { + return 200 test.version; + } + + location /hello { + js_content test.hello; + } + + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + + root html; + } +} + +``` + +编辑js 脚本 +``` +function hello(r) { + r.return(200, "Hello from njs!\n"); +} + +export default {hello, version: "1.0.0"}; +``` + + +##### 访问测试 + +测试配置是否正确 + +``` + sbin/nginx -t + +``` + +启动nginx +``` + sbin/nginx + +``` + +访问测试 +``` +[root@cdh-node-3 nginx]# curl 127.0.0.1:80/njs +test.version[root@cdh-node-3 nginx]# curl 127.0.0.1:80/hello +Hello from njs! + +``` +