基于javascript處理nginx請求過程詳解
nginx是一個HTTP和反向代理服務器,目前很多網(wǎng)站都在使用nginx作為反向代理服務器。
njs是JavaScript語言的一個子集,它允許擴展nginx的功能,這點跟lua有點類似,不過采用的語言是javascript。
1. 安裝nginx
要使用njs,需要安裝一個nginx,這里的我使用的環(huán)境是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系統(tǒng),則使用下面的命令
# 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 librarynginx 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根目錄中創(chuàng)建一下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指令及案例,可以在官網(wǎng)中查閱 http://nginx.org/en/docs/njs/index.html。
案例地址:http://nginx.org/en/docs/njs/examples.html。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
JavaScript實現(xiàn)網(wǎng)頁計算器功能
這篇文章主要為大家詳細介紹了JavaScript實現(xiàn)網(wǎng)頁計算器功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-10-10