search
HomeBackend DevelopmentPHP TutorialNginx HTTP filter module development

Nginx filter module

Development steps of HTTP filter module

  1. Determine the source code file name;
  2. Create a config script and add the directory when configure is executed;
  3. Define the filter module and instantiate a module of type ngx_module_t Structure;
  4. Process configuration items of interest by setting the ngx_command_t array in the ngx_module_t structure;
  5. Implement the initialization function. The initialization method is to insert the ngx_http_output_header_filter_t and ngx_http_output_body_filter_t functions into the head of the filter module list;
  6. Implement ngx_http_output_header_ filter_pt and ngx_http_output_body_filter_pt functions;
  7. After compilation and installation, modify the filter module option in the nginx.conf configuration file to enable it or not.

Configuration script

<code>ngx_add

HTTP_FILTER_MODULES=<span>"<span>$HTTP_FILTER_MODULES</span> ngx_http_myfilter_module"</span>
NGX_ADD>"<span>$NGX_ADDON_SRCS</span><span>$ngx_addon_dir</span>/ngx_http_myfilter_module.c"</code>

Module content

<code><span>#include <..></..></span><span>#include <..></..></span><span>#include <..></..></span><span>//Declare</span><span>static</span> ngx_int_t ngx_http_myfilter_header_filter(ngx_http_request_t *);
<span>static</span> ngx_int_t ngx_http_myfilter_body_filter(ngx_http_request_t*,ngx_chain_t*);
<span>static</span> ngx_http_output_header_filter_pt ngx_http_next_header_filter;
<span>static</span> ngx_http_output_body_filter_pt ngx_http_next_body_filter;


<span>//On/Off</span><span>typedef</span><span>struct</span> {
    ngx_flag_t enable;
}ngx_http_myfilter_conf_t;

<span>static</span><span>void</span> *ngx_http_myfilter_create_conf(ngx_conf_t *cf){
    ngx_http_myfilter_conf_t *mycf;

    <span>//Allocate memory</span>
    mycf = (ngx_http_myfilter_conf_t*)ngx_pcalloc(cf->pool,<span>sizeof</span>(ngx_http_myfilter_conf_t));
    <span>if</span>(mycf == <span>NULL</span>)
        <span>return</span><span>NULL</span>;

    mycf->enable = NGX_CONF_UNSET;

    <span>return</span> mycf;
}

<span>static</span><span>char</span> *
ngx_http_myfilter_merge_conf(ngx_conf_t *cf,<span>void</span> *parent,<span>void</span> *child){
    ngx_http_myfilter_conf_t *prev = (ngx_http_myfilter_conf_t*)parent;
    ngx_http_myfilter_conf_t *conf = (ngx_http_myfilter_conf_t*)child;
    ngx_conf_merge_value(conf->enable,prev->enable,<span>0</span>);
    <span>return</span> NGX_CONF_OK;
}

<span>/* ------------------------------------------- */</span><span>//State for prefix</span><span>typedef</span><span>struct</span> {
    <span>/* add_prefix = 
     * 0    the filter module is off
     * 1    can add prefix
     * 2    has been added prefix already
     */</span>
    ngx_int_t add_prefix;
} ngx_http_myfilter_ctx_t;

<span>//Analyse configure</span><span>static</span> ngx_command_t
ngx_http_myfilter_commands[]={
    {ngx_string(<span>"add_prefix"</span>),
        NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LMT_CONF|NGX_CONF_FLAG,
        ngx_conf_set_flag_slot,
        NGX_HTTP_LOC_CONF_OFFSET,
        offsetof(ngx_http_myfilter_conf_t,enable),
        <span>NULL</span>},
    ngx_null_command
};

<span>static</span> ngx_int_t
ngx_http_myfilter_init(ngx_conf_t *cf){
    <span>//Insert before the first node</span>
    ngx_http_next_header_filter = ngx_http_top_header_filter;
    ngx_http_top_header_filter = ngx_http_myfilter_header_filter;

    ngx_http_next_body_filter = ngx_http_top_body_filter;
    ngx_http_top_body_filter = ngx_http_myfilter_body_filter;

    <span>return</span> NGX_OK;
}

<span>/* ------------------------------------------- */</span><span>//Parse</span><span>static</span> ngx_http_module_t
ngx_http_myfilter_module_ctx = {
    <span>NULL</span>,
    ngx_http_myfilter_init,
    <span>NULL</span>,
    <span>NULL</span>,
    <span>NULL</span>,
    <span>NULL</span>,
    ngx_http_myfilter_create_conf,
    ngx_http_myfilter_merge_conf
};

<span>/* ------------------------------------------- */</span><span>//Module information</span>
ngx_module_t ngx_http_myfilter_module = {
    NGX_MODULE_V1,
    &ngx_http_myfilter_module_ctx,
    ngx_http_myfilter_commands,
    NGX_HTTP_MODULE,
    <span>NULL</span>,
    <span>NULL</span>,
    <span>NULL</span>,
    <span>NULL</span>,
    <span>NULL</span>,
    <span>NULL</span>,
    <span>NULL</span>,
    NGX_MODULE_V1_PADDING
};

<span>/* ------------------------------------------- */</span><span>static</span> ngx_str_t filter_prefix = ngx_string(<span>"[my filter module]"</span>);

<span>//Filter to process the header</span><span>static</span> ngx_int_t
ngx_http_myfilter_header_filter(ngx_http_request_t *r){
    ngx_http_myfilter_ctx_t *ctx;
    ngx_http_myfilter_conf_t *conf;

    <span>if</span>(r->headers_out<span>.status</span> != NGX_HTTP_OK){
        <span>return</span> ngx_http_next_header_filter(r);
    }

    <span>//Get context</span>
    ctx = ngx_http_get_module_ctx(r,ngx_http_myfilter_module);
    <span>if</span>(ctx){
        <span>return</span> ngx_http_next_header_filter(r);
    }

    <span>//Get configure by ngx_http_myfilter_conf_t</span>
    conf = ngx_http_get_module_loc_conf(r,ngx_http_myfilter_module);

    <span>if</span>(conf->enable == <span>0</span>){<span>//add_prefix off</span><span>return</span> ngx_http_next_header_filter(r);
    }

    <span>//Create ngx_http_myfilter_ctx_t</span>
    ctx = ngx_pcalloc(r->pool,<span>sizeof</span>(ngx_http_myfilter_ctx_t));
    <span>if</span>(ctx == <span>NULL</span>){
        <span>return</span> NGX_ERROR;
    }

    <span>//add_prefix = 0 express do not add prefix</span>
    ctx->add_prefix = <span>0</span>;

    <span>//Set context</span>
    ngx_http_set_ctx(r,ctx,ngx_http_myfilter_module);

    <span>//myfilter module only figure out Content-Type="text/plain"</span><span>if</span>(r->headers_out<span>.content_type</span><span>.len</span>>=<span>sizeof</span>(<span>"text/plain"</span>) - <span>1</span> &&
            ngx_strncasecmp(r->headers_out<span>.content_type</span><span>.data</span>,(u_char*)<span>"text/plain"</span>,<span>sizeof</span>(<span>"text/plain"</span>)-<span>1</span>)==<span>0</span>){
        <span>//Set add_prefix</span>
        ctx->add_prefix = <span>1</span>;
        <span>if</span>(r->headers_out<span>.content_length_n</span>><span>0</span>)
            r->headers_out<span>.content_length_n</span> += filter_prefix<span>.len</span>;
    }
        <span>return</span> ngx_http_next_header_filter(r);
}

<span>//Filter to process the body</span><span>static</span> ngx_int_t
ngx_http_myfilter_body_filter(ngx_http_request_t *r,ngx_chain_t *in){
    ngx_http_myfilter_ctx_t *ctx;
    ctx = ngx_http_get_module_ctx(r,ngx_http_myfilter_module);
    <span>//If cannot get context or the add_prefix is 0/2,do not process</span><span>if</span>(ctx == <span>NULL</span> || ctx->add_prefix !=<span>1</span>)
        <span>return</span> ngx_http_next_body_filter(r,in);

    <span>//To make sure never add prefix again</span>
    ctx->add_prefix = <span>2</span>;

    <span>//Get prefix string</span>
    ngx_buf_t *b = ngx_create_temp_buf(r->pool,filter_prefix<span>.len</span>);
    b->start = b->pos = filter_prefix<span>.data</span>;
    b->last = b->pos + filter_prefix<span>.len</span>;

    <span>//Get and set ngx_chain_t list at the bginning</span>
    ngx_chain_t *cl = ngx_alloc_chain_link(r->pool);
    cl->buf = b;
    cl->next = in;

    <span>return</span> ngx_http_next_body_filter(r,cl);
}</code>

Configuration file nginx.conf

Add
in http{} add_prefix on;
Turn on the filtering module

Compile

<code>./configure --<span>add</span>-<span>module</span>=模块路径/
make
make install</code>

The HTTP filtering module is also an HTTP module, so the writing of the HTTP module is roughly the same.

Copyright Statement: Pain is just in your mind.

The above has introduced the development of Nginx HTTP filtering module, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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),