In this njs Tutorial, we will delve into the functionalities of njs, the powerful scripting language for Nginx, providing you with the know-how to supercharge your Nginx configurations. We’ll explore everything from installation to advanced scripting tasks.
1. Installation
Begin by installing njs for Nginx. You can do this by using the package manager that corresponds with your operating system:
sudo apt-get install nginx-module-njs # For Ubuntu sudo yum install nginx-module-njs # For CentOS
Once installed, confirm that njs is available by running:
nginx -V 2>&1 | grep ngx_http_js_module
If the module is correctly installed, you should see ‘ngx_http_js_module’ in the output.
2. Loading njs in nginx.conf
To use njs, you must load it in your Nginx configuration:
load_module modules/ngx_http_js_module.so;
This line should be added at the top of your nginx.conf file. After adding the module, reload the Nginx configuration:
sudo nginx -s reload
3. Hello World Example
A simple “Hello World” script in njs:
function helloWorld(r) {
r.return(200, "Hello World!");
}
export default { helloWorld };
To call this function in your Nginx configuration:
js_import hello_world from '/path/to/helloworld.js';
location /hello {
js_content hello_world.helloWorld;
}
After reloading Nginx, visiting /hello will display:
Output: Hello World!
4. Reading HTTP Headers
Reading an HTTP header in njs is straightforward. Here’s an example function:
function readHeader(r) {
var host = r.headersIn.Host;
r.return(200, "Host: " + host);
}
export default { readHeader };
Wire this up in your Nginx configuration like so:
js_import header_reader from '/path/to/readHeader.js';
location /read-header {
js_content header_reader.readHeader;
}
Visiting /read-header will return the value of the Host header used in the request.
5. Modifying HTTP Headers
To modify HTTP headers using njs, you can manipulate the r.headersOut object:
function modifyHeaders(r) {
r.headersOut['X-Custom-Header'] = 'Added by njs';
r.return(200, "Headers modified!");
}
export default { modifyHeaders };
Add this function’s invocation to your site configuration:
js_import header_modifier from '/path/to/modifyHeaders.js';
location /modify-headers {
js_content header_modifier.modifyHeaders;
}
Now, the response at /modify-headers will contain the custom header value.
6. Modifying the Response
To alter the response body in njs:
function modifyResponse(r) {
r.subrequest('/api/data', function(res) {
var content = JSON.parse(res.responseBody);
content.modified = true;
r.return(200, JSON.stringify(content));
});
}
export default { modifyResponse };
Implement the above function in your Nginx configuration:
js_import response_modifier from '/path/to/modifyResponse.js';
location /modify-response {
js_content response_modifier.modifyResponse;
}
This script makes a subrequest to /api/data, modifies the response, and returns it.
7. Asynchronous HTTP Requests
njs can handle asynchronous HTTP requests using the r.subrequest() method:
function fetchExternalAPI(r) {
r.subrequest('/internal-proxy', function(res) {
r.return(res.status, res.responseBody);
});
}
export default { fetchExternalAPI };
Incorporate the function into Nginx’s configuration:
js_import external_api_fetcher from '/path/to/fetchExternalAPI.js';
location /internal-proxy {
proxy_pass http://api.external-service.com/data;
}
location /fetch-api {
js_content external_api_fetcher.fetchExternalAPI;
}
The script proxies a local endpoint to an external service and fetches data asynchronously.
8. Generating JWT Tokens
To generate JWT tokens with njs:
var crypto = require('crypto');
function generateJWT(r) {
var header = {"typ":"JWT","alg":"HS256"};
var payload = {"user":"nginx-user"};
var base64Header = Buffer.from(JSON.stringify(header), 'utf8').toString('base64');
var base64Payload = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');
var signature = crypto.createHmac('sha256', 'secret')
.update(base64Header + '.' + base64Payload)
.digest('base64');
var jwt = base64Header + '.' + base64Payload + '.' + signature;
r.return(200, jwt);
}
export default { generateJWT };
Activate the JWT generation in the Nginx config file:
js_import jwt_generator from '/path/to/generateJWT.js';
location /generate-jwt {
js_content jwt_generator.generateJWT;
}
When /generate-jwt is accessed, it produces a signed JWT.
9. Conclusion
By following this tutorial, you should now have a good understanding of njs and how to harness its power for scripting within Nginx. From simple configurations like a “Hello World” response to more complex examples like modifying headers and making asynchronous HTTP requests, njs opens up a world of possibilities for dynamic web content management.
Remember, njs is a versatile tool and its potential applications are vast. With practice and exploration, you can integrate njs into your Nginx setup to achieve high performance and customization in your web applications.
10. References
