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目錄下的日志查看啟動日志,如果啟動成功,將可以看到下面的界面:
到這里集成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返回的結果。
4. 更多njs指令
關於更多的njs指令及案例,可以在官網中查閱 http://nginx.org/en/docs/njs/index.html。
案例地址:http://nginx.org/en/docs/njs/examples.html。
就目前來說,njs並不想nginx + lua那樣,有很多第三方庫,但是畢竟njs是官方推出的,還是值得期待。
關注公眾號,閱讀更多文章。