默认情况下是nginx并没包含njs模块,需要独立安装。 本文主要介绍从源码安装的方法。
一、下载nginx源码,本文使用的版本是1.16.1
解压在目录~/nginx-1.16.1
二、下载njs源码,(首先要安装一个类似于git的版本管理工具mercurial: yum install mercurial)
~]# hg clone http://hg.nginx.org/njs (注意njs目录与nginx-1.16.1平级)
三、进入到nginx源码目录进行编译安装
cd nginx-1.16.1
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_image_filter_module --with-http_sub_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_auth_request_module --with-http_slice_module --with-http_stub_status_module --with-mail --with-mail_ssl_module --with-stream --with-stream_ssl_module --with-stream_ssl_module --with-stream_realip_module --with-stream_ssl_preread_module --with-pcre --add-module=../njs/nginx
(起关键作用的是 --add-module=../njs/nginx, 模块路径要正确, 其它配置视自身情况而定)
四、编写njs脚本进行测试
在/usr/local/nginx/conf目录下新建脚本hello_world.js (为了验证方便就没有指定到别的目录),其内容如下:
function hello(r){
r.return(200, "Hello world");
}
保存退出。
编辑nginx.conf文件,添加如下配置:
http {
js_include hello_world.js; #Added
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
js_content hello; //Added
}
...
保存退出。
运行命令启动nginx服务:/usr/local/nginx/sbin/nginx
测试:curl -i localhost
可以看到输出了Hello world.
说明安装成功。
注意网上有些文章说要在nginx.conf中加入此配置项:load_module modules/ngx_http_js_module.so;
参考:
https://nginx.org/en/docs/njs/install.html#install_package (官方安装方法,njs命令行式交互工具也有介绍,可方便测试njs)
https://nginx.org/en/docs/njs (官方示例)
更多示例:https://github.com/xeioex/njs-examples