NGINX Modern Apps > Class 3 - NGINX Dataplane Scripting Source | Edit on
Complex redirects using njs file map. [http/complex_redirects]¶
In this example, we will use njs to use a online mapping table to transform a request’s URI before proxing to the upstream.
Step 1: Use the following commands to start your NGINX container with this lab’s files: Notice that we are now exposing port 8090
Step 2: Now let’s use curl to test our NGINX server:
curl http://localhost/CCC?a=1
200 /CCC?a=1
curl http://localhost:8090/map
200 {}
curl http://localhost:8090/add -X POST --data '{"from": "/CCC", "to": "/AA"}'
200
curl http://localhost:8090/add -X POST --data '{"from": "/BBB", "to": "/DD"}'
200
curl http://localhost/CCC?a=1
200 /AA?a=1
curl http://localhost/BB?a=1
200 /BB?a=1
curl http://localhost:8090/map
200 {"/CCC":"/AA","/BBB":"/DD"}
curl http://localhost:8090/remove -X POST --data '{"from": "/CCC"}'
200
curl http://localhost:8090/map
200 {"/BBB":"/DD"}
curl http://localhost/CCC?a=1
200 /CCC?a=1
docker stop njs_example
Code Snippets¶
This config uses auth_request to make a request to an “authentication server” before proxyingto the upstream server. In this case, the “auth server” is an internal location that calls our njs code. The data returned by our code is put into the $route variable which is used to build a new URI to be proxied to the upstream server.
This njs code grabs the first element of the request URI to query the mapping table DB. If an entry exists, the original URI is replaced with the new one. The new URI is passed back to NGINX in a new “Route” header.