使用javascript处理nginx的请求

nginx是一个HTTP和反向代理服务器,目前很多网站都在使用nginx作为反向代理服务器。
njs是JavaScript语言的一个子集,它允许扩展nginx的功能,这点跟lua有点类似,不过采用的语言是javascript。

1. 安装nginx

njs作为nginx的模块,需要编到nginx中,这里的我使用的环境是Ubuntu18.04.4。
首先从http://nginx.org/en/download.html下载最新的stable version的nginx源码。

a. 解压源码

sudo tar zxvf nginx-1.18.0.tar.gz

b. 安装必要依赖库

sudo apt-get install libpcre3 libpcre3-dev
sudo apt-get install zlib1g-dev
sudo apt-get install openssl libssl-dev 
# 如果是Centos系统,则使用下面的命令
# yum install pcre pcre-devel
# yum install zlib zlib-devel
# yum install openssl-devel

c. 拉取njs源码

# 安装mercurial
sudo apt-get install mercurial
# 拉取源码
cd /usr/local/src
hg clone http://hg.nginx.org/njs

d. 配置nginx

cd nginx-1.18.0
sudo ./configure 
    --sbin-path=/usr/local/nginx/nginx 
    --conf-path=/usr/local/nginx/nginx.conf 
    --pid-path=/usr/local/nginx/nginx.pid 
    --add-module=/usr/local/src/njs/nginx

如果配置成功,可以看到如下信息:

Configuration summary
  + using system PCRE library
  + OpenSSL library is not used
  + using system zlib library

  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/nginx"
  nginx modules path: "/usr/local/nginx/modules"
  nginx configuration prefix: "/usr/local/nginx"
  nginx configuration file: "/usr/local/nginx/nginx.conf"
  nginx pid file: "/usr/local/nginx/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

e. 编译源码

sudo make
# 如果没有安装make指令,可以通过下面的命令安装
# sudo apt-get install make

f. 安装

sudo make install
# 安装目录为/usr/local/nginx

g. 启动nginx

cd  /usr/local/nginx
sudo ./nginx

启动后可以通过访问http://localhost查看nginx是否启动成功,也可以通过logs目录下的日志查看启动日志,如果启动成功,将可以看到下面的界面:

nginx

到这里集成njs的nginx就安装完成了,下面可以开始写javascript代码了。

2. 编写js代码

在nginx根目录中创建一下js目录用存放所有的js程序,并编写http.js测试njs模块是否集成完成。

sudo mkdir js
cd js
sudo touch http.js

http.js的源码,这里只是简单的输出Hello world这个字符串。

function hello(r) {
    r.return(200, "Hello world!");
}

export default {hello};

3. 引入js程序

http.js编写完成后,需要引入到nginx中,修复nginx.conf配置,下面省略了其他相关配置

http {
  # 引入http程序
  js_import js/http.js;

  server {
    location /js {
      default_type 'text/html';
      js_content http.hello;
    }
  }
}

上面指定了/js路径的处理由http.hello程序处理,这样可以通过浏览器访问http://localhost/js来查看http.hello返回的结果。

njs

4. 更多njs指令

关于更多的njs指令及案例,可以在官网中查阅 http://nginx.org/en/docs/njs/index.html。
案例地址:http://nginx.org/en/docs/njs/examples.html。

就目前来说,njs并不想nginx + lua那样,有很多第三方库,但是毕竟njs是官方推出的,还是值得期待。

HiIT青年
关注公众号,阅读更多文章。

原文地址:https://www.cnblogs.com/itqn/p/nginx_njs.html