首页 web服务器 正文
5688

nginx添加njs(又名nginScript )模块

      有一个阿里的程序员在nginx服务器下开发了一个基于LuaJit的nignx插件模块,使nginx中使用lua脚本进行各种http hook成为可能, 并不断发展壮大这个插件使其成为了一个基于nignx与lua的上层平台,名叫openresty,非常强大且高性能,京东、淘宝等都有使用它。此平台非常适合支撑api服务,WAF服务,cdn服务等。nginx官方不知道是不是受此启发,推出了nginScript, 基于nginx运行环境下的javascript编程, 它是javascript的子集,有自己更精简的虚拟机,对于控制nginx提供了更灵活的编程手段。

默认情况下是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, 模块路径要正确, 其它配置视自身情况而定)

make && make install

四、编写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;
可能是某些nginx历史版本才需要,请读者自行判别。

参考:
https://nginx.org/en/docs/njs/install.html#install_package  (官方安装方法,njs命令行式交互工具也有介绍,可方便测试njs)
https://nginx.org/en/docs/njs  (官方示例)
更多示例:https://github.com/xeioex/njs-examples

正在加载评论...