基于javascript处理nginx请求过程详解
nginx是一个HTTP和反向代理服务器,目前很多网站都在使用nginx作为反向代理服务器。
njs是JavaScript语言的一个子集,它允许扩展nginx的功能,这点跟lua有点类似,不过采用的语言是javascript。
1.安装nginx
要使用njs,需要安装一个nginx,这里的我使用的环境是Ubuntu18.04.4。
首先从http://nginx.org/en/download.html下载最新的stableversion的nginx源码。
a.解压源码
sudotarzxvfnginx-1.18.0.tar.gz
b.安装必要依赖库
sudoapt-getinstalllibpcre3libpcre3-dev
sudoapt-getinstallzlib1g-dev
sudoapt-getinstallopenssllibssl-dev
#如果是Centos系统,则使用下面的命令
#yuminstallpcrepcre-devel
#yuminstallzlibzlib-devel
#yuminstallopenssl-devel
c.拉取njs源码
#安装mercurial
sudoapt-getinstallmercurial
#拉取源码
cd/usr/local/src
hgclonehttp://hg.nginx.org/njs
d.配置nginx
cdnginx-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
如果配置成功,可以看到如下信息:
Configurationsummary
+usingsystemPCRElibrary
+OpenSSLlibraryisnotused
+usingsystemzliblibrarynginxpathprefix:"/usr/local/nginx"
nginxbinaryfile:"/usr/local/nginx/nginx"
nginxmodulespath:"/usr/local/nginx/modules"
nginxconfigurationprefix:"/usr/local/nginx"
nginxconfigurationfile:"/usr/local/nginx/nginx.conf"
nginxpidfile:"/usr/local/nginx/nginx.pid"
nginxerrorlogfile:"/usr/local/nginx/logs/error.log"
nginxhttpaccesslogfile:"/usr/local/nginx/logs/access.log"
nginxhttpclientrequestbodytemporaryfiles:"client_body_temp"
nginxhttpproxytemporaryfiles:"proxy_temp"
nginxhttpfastcgitemporaryfiles:"fastcgi_temp"
nginxhttpuwsgitemporaryfiles:"uwsgi_temp"
nginxhttpscgitemporaryfiles:"scgi_temp"
e.编译源码
sudomake
#如果没有安装make指令,可以通过下面的命令安装
#sudoapt-getinstallmake
f.安装sudomakeinstall
#安装目录为/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模块是否集成完成。
sudomkdirjs
cdjs
sudotouchhttp.js
http.js的源码
functionhello(r){ r.return(200,"Helloworld!"); } exportdefault{hello};
3.引入js程序
http.js编写完成后,需要引入到nginx中,修复nginx.conf配置,下面省略了其他相关配置
http{ #引入http程序 js_importjs/http.js; server{ location/js{ default_type'text/html'; js_contenthttp.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。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。