Using Lua Nginx module for dynamic routing based on Redis values

Working with Nginx modules can bring amazing flexibility to customize and make the Nginx server more powerful by using third-party modules, but the struggle is to actually get these things working together. By the end of this article, you should be able to build and run Nginx server on Ubuntu 20.04 and use “User-Agent” header from the incoming request to route it to different HTTP backend based on Redis store values.

This article assumes that you have fundamental knowledge working with Nginx.
There are two ways to get Nginx up and running:
1. Install Nginx as a prebuilt-package
2. Build Nginx from the source with other modules (an approach we are following in this article)

I. Installing Required Packages:

II. Downloading source files for Nginx and Modules:

We are downloading the open-source version of Nginx - nginx.org, often confused with the paid platform - nginx.com.

III. Extracting the source files using the following commands

IV. Building LUAJIT and Nginx

Configuring the nginx source code to run with the modules. To do this, run the ./configure script from nginx source code installation folder. ./configure script also gives the errors for any missing libraries which can be installed using “sudo apt-get install …”

Two modules added to nginx are ngx_devel_kit and lua-nginx-module. lua-resty-redis does not have to be added ./configure script arguments as it is not an Nginx C module, it is a pure Lua library that can be directly required from within your Lua code in the nginx.conf file.

V. Starting Redis as a service

Check out more information about Redis setup here. Follow the link to configure Nginx server to add virtual host details for dynamic routing.

NOTE:
Add lua_package_path to nginx.conf to find lua-resty-redis module.

VI. Running Nginx as a service

VII. Testing dynamic routing with curl

You can find the reference for nginx.conf file here.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store