search
HomeOperation and MaintenanceNginxNginx Module Mastery: Extending Functionality with Lua & Custom Modules

Nginx's functionality can be extended through Lua scripts and custom modules. 1) Use the ngx_http_lua_module module to execute Lua code in Nginx to implement dynamic configuration and complex request processing. 2) Develop custom modules using C language, directly interact with Nginx core, and implement underlying function extensions, such as adding HTTP headers.

Nginx Module Mastery: Extending Functionality with Lua & Custom Modules

introduction

In modern web development, Nginx has become the first choice for many developers as a high-performance reverse proxy and load balancer. However, relying solely on the basic functions of Nginx is often not enough to meet complex business needs. That's why we need to dig deep into how to extend Nginx's capabilities with Lua scripts and custom modules. This article will take you to gradually master the development and application of Nginx modules from scratch, helping you solve various challenges in actual projects.

By reading this article, you will learn how to use Lua scripts to implement dynamic configuration, complex request processing logic in Nginx, and how to develop and integrate custom modules to enhance Nginx's functionality. Whether you are a beginner or an experienced developer, you can benefit greatly from it.

Review of basic knowledge

Nginx itself is a powerful web server, but its real power lies in its modular design. Nginx's modules can be divided into core modules, standard HTTP modules, optional HTTP modules and third-party modules. Lua scripts are integrated into Nginx through the ngx_http_lua_module module, allowing us to execute Lua code in Nginx, thereby achieving more flexible request processing and response generation.

Lua is a lightweight scripting language that is ideal for embedding into applications. Its syntax is simple and execution is efficient, and it is especially suitable for dynamic configuration and complex logic processing in Nginx.

Core concept or function analysis

Application of Lua in Nginx

The main function of Lua scripts in Nginx is to provide dynamic configuration and complex request processing logic. Through the ngx_http_lua_module module, we can execute Lua code at various stages of Nginx (such as rewrite, access, content, etc.), thereby achieving more flexible request processing.

For example, we can use Lua scripts to implement dynamic load balancing strategies, or generate response content dynamically based on request parameters. Here is a simple Lua script example for returning a custom response in Nginx:

 -- Define a simple Lua script function handle_request()
    ngx.say("Hello, Nginx with Lua!")
end

-- Call this function handle_request() in the content stage of Nginx

This script will be executed in the content stage of Nginx, returning a simple string response.

Development and integration of custom modules

In addition to Lua scripts, we can also extend the functionality of Nginx by developing custom modules. Custom modules can directly interact with Nginx's core functions to achieve lower-level function expansion.

Developing custom modules requires a certain understanding of Nginx's source code and needs to be written in C language. Here is a simple custom module example for adding a new HTTP header in Nginx:

 #include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>

typedef struct {
    ngx_str_t header_name;
    ngx_str_t header_value;
} ngx_http_custom_header_loc_conf_t;

static ngx_int_t ngx_http_custom_header_init(ngx_conf_t *cf);

static void *ngx_http_custom_header_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_custom_header_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child);

static ngx_command_t ngx_http_custom_header_commands[] = {
    { ngx_string("custom_header"),
      NGX_HTTP_LOC_CONF|NGX_CONF_TAKE2,
      ngx_conf_set_key_val_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_custom_header_loc_conf_t, header_name),
      NULL },

    ngx_null_command
};

static ngx_http_module_t ngx_http_custom_header_module_ctx = {
    NULL, /* preconfiguration */
    ngx_http_custom_header_init, /* postconfiguration */

    NULL, /* create main configuration */
    NULL, /* init main configuration */

    NULL, /* create server configuration */
    NULL, /* merge server configuration */

    ngx_http_custom_header_create_loc_conf, /* create location configuration */
    ngx_http_custom_header_merge_loc_conf /* merge location configuration */
};

ngx_module_t ngx_http_custom_header_module = {
    NGX_MODULE_V1,
    &ngx_http_custom_header_module_ctx, /* module context */
    ngx_http_custom_header_commands, /* module directives */
    NGX_HTTP_MODULE, /* module type */
    NULL, /* init master */
    NULL, /* init module */
    NULL, /* init process */
    NULL, /* init thread */
    NULL, /* exit thread */
    NULL, /* exit process */
    NULL, /* exit master */
    NGX_MODULE_V1_PADDING
};

static ngx_int_t ngx_http_custom_header_handler(ngx_http_request_t *r)
{
    ngx_http_custom_header_loc_conf_t *clcf;

    clcf = ngx_http_get_module_loc_conf(r, ngx_http_custom_header_module);

    if (clcf->header_name.len > 0 && clcf->header_value.len > 0) {
        ngx_table_elt_t *h = ngx_list_push(&r->headers_out.headers);
        if (h == NULL) {
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }

        h->hash = 1;
        ngx_str_set(&h->key, clcf->header_name.data);
        ngx_str_set(&h->value, clcf->header_value.data);
    }

    return NGX_DECLINED;
}

static ngx_int_t ngx_http_custom_header_init(ngx_conf_t *cf)
{
    ngx_http_handler_pt *h;
    ngx_http_core_main_conf_t *cmcf;

    cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

    h = ngx_array_push(&cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers);
    if (h == NULL) {
        return NGX_ERROR;
    }

    *h = ngx_http_custom_header_handler;

    return NGX_OK;
}

static void *ngx_http_custom_header_create_loc_conf(ngx_conf_t *cf)
{
    ngx_http_custom_header_loc_conf_t *conf;

    conf = ngx_palloc(cf->pool, sizeof(ngx_http_custom_header_loc_conf_t));
    if (conf == NULL) {
        return NGX_CONF_ERROR;
    }

    return conf;
}

static char *ngx_http_custom_header_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
{
    ngx_http_custom_header_loc_conf_t *prev = parent;
    ngx_http_custom_header_loc_conf_t *conf = child;

    ngx_conf_merge_str_value(conf->header_name, prev->header_name, "");
    ngx_conf_merge_str_value(conf->header_value, prev->header_value, "");

    return NGX_CONF_OK;
}

This module will add a custom HTTP header in the content stage of Nginx. We can set this header by using the custom_header directive in the Nginx configuration file, for example:

 http {
    ...
    server {
        listen 80;
        server_name example.com;

        location / {
            custom_header X-Custom-Header "Custom Value";
            ...
        }
    }
}

Example of usage

Basic usage

Using Lua scripts to implement dynamic configuration in Nginx is very simple. We can use the API provided by the ngx_lua module to operate Nginx configuration and request processing. For example, the following is a simple Lua script that returns different response content based on the request parameters:

 -- Return different response content according to the request parameter local args = ngx.req.get_uri_args()
if args.name then
    ngx.say("Hello, " .. args.name .. "!")
else
    ngx.say("Hello, World!")
end

This script will be executed in the content stage of Nginx, and returns different response contents according to the request parameter name .

Advanced Usage

In actual projects, we may need to implement more complex logic, such as dynamic load balancing, request rewriting, cache management, etc. Here is an example of dynamic load balancing using Lua scripts:

 -- Define a load balancer local balancer = require "ngx.balancer"

-- Define the backend server list local servers = {
    { host = "backend1.example.com", port = 80 },
    { host = "backend2.example.com", port = 80 },
    { host = "backend3.example.com", port = 80 }
}

-- Select a backend server local server = servers[math.random(#servers)]

-- Set load balancer local ok, err = balancer.set_current_peer(server.host, server.port)
If not ok then
    ngx.log(ngx.ERR, "failed to set the current peer: ", err)
    return ngx.exit(500)
end

-- Continue to process the request return ngx.exec("@backend")

This script will be executed in the balancer stage of Nginx and load balancing is performed based on the randomly selected backend server.

Common Errors and Debugging Tips

When using Lua scripts and custom modules, you may encounter some common errors, such as syntax errors, runtime errors, configuration errors, etc. Here are some common errors and their debugging tips:

  • Syntax error : Use the luac command line tool to check the syntax of Lua scripts, such as luac -p script.lua .
  • Runtime Error : Enable error logs in Nginx configuration file, such as error_log /path/to/error.log debug; and then view the details in the error log.
  • Configuration error : Double-check the syntax and logic in the Nginx configuration file to ensure that all configuration items are correct.

Performance optimization and best practices

In practical applications, how to optimize the performance of Lua scripts and custom modules is a key issue. Here are some recommendations for performance optimization and best practices:

  • Reduce the number of executions of Lua scripts : Try to execute Lua scripts in the early stages of Nginx (such as rewrite and access stages) to avoid executing too much Lua code in the content stage.
  • Use caching : Use Nginx's caching mechanism (such as ngx.shared.DICT ) to cache the execution results of Lua scripts to reduce duplicate calculations.
  • Optimize Lua code : Use the LuaJIT compiler to optimize the execution efficiency of Lua scripts and reduce memory usage and CPU consumption.

When writing Lua scripts and custom modules, you also need to pay attention to the readability and maintenance of the code. Here are some best practices:

  • Use meaningful variable names and function names : improve the readability of the code, making it easier for other developers to understand and maintain.
  • Add detailed comments : Add detailed comments to the code to explain complex logic and critical implementation details.
  • Follow code specifications : Follow code specifications in Lua and C languages ​​to maintain code consistency and maintainability.

Through this article, you have mastered how to extend the functionality of Nginx through Lua scripts and custom modules. Whether it’s solving complex business needs in real projects or improving work efficiency in daily development, these knowledge and skills will be of great help to you. Hope you can continue to explore more possibilities of Nginx and achieve its maximum potential.

The above is the detailed content of Nginx Module Mastery: Extending Functionality with Lua & Custom Modules. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I configure Nginx for server-side includes (SSI)?How do I configure Nginx for server-side includes (SSI)?Mar 17, 2025 pm 05:06 PM

The article discusses configuring Nginx for server-side includes (SSI), performance implications, using SSI for dynamic content, and troubleshooting common SSI issues in Nginx.Word count: 159

How do I implement HTTP authentication (basic auth, digest auth) in Nginx?How do I implement HTTP authentication (basic auth, digest auth) in Nginx?Mar 17, 2025 pm 05:03 PM

The article discusses implementing HTTP authentication in Nginx using basic and digest methods, detailing setup steps and security implications. It also covers using authentication realms for user management and suggests combining authentication meth

How do I configure Nginx for URL rewriting and redirection?How do I configure Nginx for URL rewriting and redirection?Mar 17, 2025 pm 05:02 PM

The article discusses configuring Nginx for URL rewriting and redirection, detailing steps and best practices. It addresses common mistakes and testing methods to ensure effective URL management.

What are the best tools for monitoring Nginx?What are the best tools for monitoring Nginx?Mar 17, 2025 pm 05:09 PM

The article discusses top Nginx monitoring tools like Datadog, New Relic, and NGINX Amplify, focusing on their features for real-time monitoring, alerting, and detailed metrics to enhance server performance.

How do I monitor Nginx performance and resource usage?How do I monitor Nginx performance and resource usage?Mar 17, 2025 pm 05:08 PM

The article discusses monitoring and optimizing Nginx performance, focusing on using tools like Nginx's status page, system-level monitoring, and third-party solutions like Prometheus and Grafana. It emphasizes best practices for performance optimiza

How does Nginx handle request processing and worker processes?How does Nginx handle request processing and worker processes?Mar 14, 2025 pm 04:13 PM

Nginx uses a master-worker model to handle requests efficiently. Worker processes manage thousands of connections using event-driven, non-blocking I/O. Performance optimization involves adjusting worker processes, connections, and configuration setti

How does Nginx compare to Apache web server?How does Nginx compare to Apache web server?Mar 14, 2025 pm 04:09 PM

The article compares Nginx and Apache, focusing on their architecture, performance, and use cases. Nginx's event-driven model offers better performance under high traffic, while Apache is favored for dynamic content and ease of configuration for begi

What Are the Best Strategies for Managing SSL/TLS Certificates on Nginx?What Are the Best Strategies for Managing SSL/TLS Certificates on Nginx?Mar 11, 2025 pm 05:13 PM

This article details best practices for managing SSL/TLS certificates on Nginx. It emphasizes automation via tools like Certbot and cloud services, proper configuration (including strong ciphers), regular monitoring for expiration and vulnerabilitie

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)