nginx JavaScript 模組
njs 是一個 nginx 模組,透過 JavaScript 腳本擴展伺服器的功能,實現客製化的伺服器端邏輯和更多功能。
使用案例
- 在請求到達上游伺服器之前,在 njs 中進行複雜的存取控制和安全檢查
- 操作回應標頭
- 撰寫彈性的非同步內容處理器和篩選器
請參閱範例,了解更多 njs 使用案例。
基本 HTTP 範例
在 nginx 中使用 njs
-
安裝 njs 腳本語言
-
建立一個 njs 腳本檔案,例如
http.js
。請參閱參考以取得 njs 屬性和方法的列表。function hello(r) { r.return(200, "Hello world!"); } export default {hello};
-
在
nginx.conf
檔案中,啟用ngx_http_js_module 模組,並使用http.js
腳本檔案指定 js_import 指令。load_module modules/ngx_http_js_module.so; events {} http { js_import http.js; server { listen 8000; location / { js_content http.hello; } } }
還有一個獨立的命令列工具,可以獨立於 nginx 使用,用於 njs 開發和除錯。
已測試的作業系統和平台
- FreeBSD / amd64;
- Linux / x86, amd64, arm64, ppc64el;
- Solaris 11 / amd64;
- macOS / x86_64;