我们从结果倒推安装过程
先看njs安装成功后的 nginx.conf,了解需要什么东西
查看nginx.conf 所在目录
mac ~: nginx -t
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
nginx.conf
//这里必须写到nginx配置第一行
load_module modules/ngx_http_js_module.so;
http {
//指定我们的js脚本所在目录
js_path "/etc/nginx/njs/";
js_import hello.js;
server {
listen 8088;
location /hello {
js_content main.hello;
}
}
/etc/nginx/njs/hello.js
function hello(r){
r.return(200,"hello");
}
export default {hello};
浏览器访问 http://127.0.0.1:8088/hello
显示 hello
可以看到,我们需要ngx_http_js_module.so 这个文件,而这个文件需要在本地编译出来,同时需要一个hello.js 脚本,用于安装后需求实现。该文件要放到 js_path 指定的目录下,如果不设置js_path,则默认是nginx.conf 所在目录。
编译ngx_http_js_module.so
编译需要 njs源码 和 nginx源码(需与本地已安装nginx服务版本一致)
下载nginx源码只是用来编译so,不影响本地已经安装的nginx服务
查看本地nginx版本
mac ~: nginx -v
nginx version: nginx/1.25.4
下载nginx源码,并切换版本与本地一致
mac ~: git clone https://github.com/nginx/nginx.git
mac ~: cd nginx
//这个指令只是合并了读取本地nginx版本和git checkout 的操作
mac ~: git checkout $( git tag | grep $( nginx -v 2>&1 | awk '{print substr($3, 7, length($3) - 6)}' ))
下载njs源码
mac ~: git clone https://github.com/nginx/njs.git
将 njs 和nginx 我们下载到了同一个目录
然后进入刚下在的nginx源码目录
mac ~: ls
nginx njs ...
mac ~: cd nginx
mac nginx: eval ./auto/configure --add-dynamic-module=../njs/nginx $( nginx -V 2>&1 | tail -n 1 | awk '{$1=$2=""; print $0}' )
之所以让下载的nginx源码和njs在同一目录下,就是因为 ../njs/nginx 这个。因为当前是在刚下载的nginx源码目录内,而要找到njs源码目录,则需要一次 cd ..
你也可以把njs下载到其他目录,--add-dynamic-module 需要同步
执行完会在刚下载的nginx源码目录下生成一个objs文件
objs
├── addon
│ ├── external
│ └── nginx
├── src
│ ├── core
│ ├── event
│ │ ├── modules
│ │ └── quic
│ ├── http
│ │ ├── modules
│ │ │ └── perl
│ │ ├── v2
│ │ └── v3
│ ├── mail
│ ├── misc
│ ├── os
│ │ ├── unix
│ │ └── win32
│ └── stream
├── Makefile
├── autoconf.err
├── ngx_auto_config.h
├── ngx_auto_headers.h
├── ngx_http_js_module_modules.c
├── ngx_modules.c
└── ngx_stream_js_module_modules.c
最下面那几个就是多出来的
然后就是编译so了
mac ~: cd nginx
mac nginx: make modules
mac nginx: ls objs
Makefile ngx_http_js_module_modules.o
addon ngx_modules.c
autoconf.err ngx_stream_js_module.so
ngx_auto_config.h ngx_stream_js_module_modules.c
ngx_auto_headers.h ngx_stream_js_module_modules.o
ngx_http_js_module.so src
ngx_http_js_module_modules.c
你讲看到两个so文件,把他们拷贝到本地现有nginx服务的根目录即可
mkdir "$( realpath $( where nginx | head -n 1)/../.. )/modules" && cp objs/*.so $( realpath $( where nginx | head -n 1)/../../modules )
然后nginx.conf 引入刚刚加的so,注意写到nginx.conf 的第一行
load_module modules/ngx_http_js_module.so;
然后在http下就可以使用js_import了。
重启nginx,njs安装成功