Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use njs module to introduce js script into nginx configuration

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "how to use the njs module to introduce js script in the nginx configuration", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use the njs module to introduce js script in the nginx configuration" this article.

First install the NJS module

The version of nginx is required to be greater than 1.9.11, because the load_module directive is only supported from this version.

Method 1: dynamically load the NJS module

Note: different versions of nginx require corresponding versions of NJS modules.

Put the ngx_http_js_module.so file in the modules directory of the nginx root directory

Add introduction module to nginx.conf

Load_module modules/ngx_http_js_module.so;load_module modules/ngx_stream_js_module.so; method 2: add modules at compile time

Download source code https://hg.nginx.org/njs/?_ga=2.99259804.301589667.1638621670-451035464.1638621670

The warehouse is managed in mercurial, and the source code needs to be downloaded using the hg command.

Hg clone http://hg.nginx.org/njs

The following configuration is added when nginx compiles

. / configure-- the characteristics of the running environment of add-module=/njs/nginx II NJS module

NJS module does not run a Nodejs, so nginx js can only be used as a middleware of nginx like lua module, not as a complete background service independently.

It is different from the node or browser running environment familiar to the front-end students. Njs does not use a V8 parsing engine. Nginx officially customizes a parsing engine based on the ECMAScript language specification. Therefore, the supported syntax and features are also different from the standard.

1. Create a runtime environment on each request and destroy it at the end of the request

The virtual machine started by node runtime is resident in memory, and the virtual machine will garbage collect the memory automatically.

NJS creates a new virtual machine and allocates memory at each request, destroys the virtual machine and frees memory at the end of the request.

two。 Non-blocking code execution

Njs uses an event-driven model to schedule the NJS runtime environment. When NJS performs blocking operations, such as reading network data or making external subrequests, Nginx suspends the execution of the current NJS VM and reschedules when the event completes. So the NJS code can be written in a simple linear way.

3. Only some syntax of ECAMA specification is supported.

NJS is based on the ECMAScript 5.1specification and supports some functions in ECMAScript 6

Supported syntax list https://nginx.org/en/docs/NJS/compatibility.html?_ga=2.91935000.301589667.1638621670-451035464.1638621670

4. Integrated request processing

The processing of requests by Nginx consists of multiple stages. Nginx instructions usually run at a specified level to process the request. The Nginx module also uses this ability to debug or modify a request.

The NJS module also runs js code logic at a specific stage in the form of instructions.

Instructions supported by NJS module and corresponding processing phase HTTP module Stream module Access-Authentication and access controlauth_request andjs_ contentjs_accessPre-read-Read/write payloadN/Ajs_prereadFilter-Read/write response during proxyjs_body_filter js_header_filterjs_filterContent-Send response to clientjs_contentN/ALog / Variables-Evaluated on demandjs_setjs_set

Simple usage example of four NJS

The following example defines a format of log using js

Create a logging.js file under the Nginx configuration directory

/ / File location: [nginx root directory] / conf/logging.js// file content: parse the request and print out all the request headers function logAllHeaders (r) {var log = `${r.variables.time_iso8601} client=$ {r.remoteAddress} method=$ {r.method} uri=$ {r.uri} status=$ {r.status}`; r.rawHeadersIn.forEach (h = > log + = `in.$ {h [0]} = ${h [1]} `) R.rawHeadersOut.forEach (h = > log + = `out.$ {h [0]} = ${h [1]} `); return log;} export default {logAllHeaders} # nginx configuration file http {js_import logging.js; # js_import loads a js script, which is placed in the nginx configuration file directory. The file name of the js will be used as the namespace for the module. When referencing a function, you can use [file name]. [function name] to reference js_set $log_all_headers logging.logAllHeaders; # js_set to save the output of the function logAllHeaders in the js file to the variable $log_all_headers. Log_format kvpairs $log_all_headers; # customize a log format kvpairs server {listen 80; access_log / var/log/nginx/access.log kvpairs; # set the log format under this rule to the above custom format root / usr/share/nginx/html;}} five instructions supported by NJS

Reference documentation

There are not many instructions supported by NJS. To achieve complex functions, you need to be used in conjunction with other Nginx instructions.

Here are a few commonly used instructions

Js_body_filter modifies the body of response

Syntax: js_body_filter function | module.function [buffer_type=string | buffer]; Default:-Context: location, limit_exceptThis directive appeared in version 0.5.2.

Example

/ * * the function that handles response body * @ param {object} r-http object * @ param {buffer_type} data-data of the requested body * @ param {boolean} flags-whether it is the last data block * / function filter (r, data, flags) {r.sendBuffer (data.toLowerCase (), flags);}

Js_content handles the return of the request

Syntax: js_content function | module.function;Default:-Context: location, limit_except

Example

Http {# introduces js module js_import http.js; server {listen 80; location / content {# specifies the js function to be executed by js_content instruction js_content http.content;}} / / http.js file function content (r) {r.status = 200 R.headersOut ['Content-Type'] = "text/plain; charset=utf-8"; r.headersOut [' Content-Length'] = 12; r.sendHeader (); r.send ("I am content"); r.finish ()} export default {content}

Js_header_filter modifies the returned request header

Syntax: js_header_filter function | module.function;Default:-Context: location, limit_exceptThis directive appeared in version 0.5.1.

Js_import imports a js file

Syntax: js_import module.js | export_name from module.js;Default:-Context: httpThis directive appeared in version 0.4.0.

Example

Http {# introduces js module. The file name will be used as the namespace for the module. When referencing a function, you can use [file name]. [function name] to refer to js_import http.js; server {listen 80; location / content {# specify the js function to be executed through the js_content instruction js_content http.content;}

Js_set setting variable

Syntax: js_set $variable function | module.function;Default:-Context: http

The function referenced by this instruction is executed when the variable is referenced for the first time. And only synchronous operations are supported in the function.

These are all the contents of the article "how to use the njs module to introduce js scripts into the nginx configuration". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report