How to Compile a Dynamic NGINX Module: A Step-by-Step Guide

NGINX is a versatile, high-performance web server, often used for reverse proxying, load balancing, and other web-related tasks. One of its strengths is the extensibility provided through modules. While there are many built-in modules, you can also compile your own dynamic modules to extend its functionality.

In this tutorial, we will guide you through the steps needed to compile a dynamic NGINX module. For demonstration purposes, we will use a hypothetical module named ngx_http_my_module.

Prerequisites

  1. NGINX source code that matches the version you’re running.
  2. A C compiler such as gcc.
  3. Development libraries for NGINX.
  4. A code editor such as Vim, Emacs, or VSCode.

Step 1: Download NGINX Source Code

First, download the NGINX source code that matches the version you are running. You can find this on the NGINX website.

wget http://nginx.org/download/nginx-1.20.0.tar.gz
tar -xzvf nginx-1.20.0.tar.gz
cd nginx-1.20.0/

Step 2: Install Dependencies

Next, install the required dependencies:

apt-get update sudo apt-get install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev openssl libssl-dev

Step 3: Prepare Your Module Code

Prepare your module’s .c source file. For this example, the file would be named ngx_http_my_module.c. Place this file in a separate directory.

Step 4: Configure and Compile NGINX

From within the NGINX source directory, configure NGINX with your module:

./configure --add-dynamic-module=/path/to/your/module make make install

If everything went well, you should see a ngx_http_my_module.so file in the objs directory.

Step 5: Load the Dynamic Module

Finally, to use your module, you’ll need to load it within your NGINX configuration file. Add the following line in your nginx.conf:

load_module "modules/ngx_http_my_module.so";

Restart NGINX:


nginx -s reload

Conclusion

Congratulations! You have successfully compiled a dynamic NGINX module. This basic tutorial should give you a starting point from which you can build more complex modules to enhance your NGINX setup. Keep coding!

Scroll to Top