2.1 KiB
2.1 KiB
nginx 使用njs模块动态修改请求
安装编译环境
#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!