1. 程式人生 > 程式設計 >基於javascript處理nginx請求過程詳解

基於javascript處理nginx請求過程詳解

nginx是一個HTTP和反向代理伺服器,目前很多網站都在使用nginx作為反向代理伺服器。
njs是JavaScript語言的一個子集,它允許擴充套件nginx的功能,這點跟lua有點類似,不過採用的語言是javascript。

1. 安裝nginx

要使用njs,需要安裝一個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的原始碼

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。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。