7. 编写并编译一个新的Nginx模块

至此,你应该可以来找一个现成的Nginx模块来看看,尝试着理解其工作原理。可以看看src/http/modules/,这里一些现成可用的模块。从里面找一个跟你想要的大概相似的模块深入地看看。看上去很熟悉?没错,应该很熟悉。对照着代码和这篇文章,慢慢理解吧。

(译者注:介于这节已不再是晦涩的概念介绍,就不做翻译了)

But Emiller didn't write a Balls-In Guide to Reading Nginx Modules. Hell no. This is a Balls-Out Guide. We're not reading. We're writing. Creating. Sharing with the world. First thing, you're going to need a place to work on your module. Make a folder for your module anywhere on your hard drive, but separate from the Nginx source (and make sure you have the latest copy from nginx.net). Your new folder should contain two files to start with:

* "config"
* "ngx_httpmodule.c"

The "config" file will be included by ./configure, and its contents will depend on the type of module.

"config" for filter modules:

ngx_addon_name=ngx_http__module
HTTP_AUX_FILTER_MODULES="$HTTP_AUX_FILTER_MODULES ngx_http__module"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http__module.c"

"config" for other modules:

ngx_addon_name=ngx_http__module
HTTP_MODULES="$HTTP_MODULES ngx_http__module"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http__module.c"

Now for your C file. I recommend copying an existing module that does something similar to what you want, but rename it "ngx_httpmodule.c". Let this be your model as you change the behavior to suit your needs, and refer to this guide as you understand and refashion the different pieces. When you're ready to compile, just go into the Nginx directory and type

./configure --add-module=path/to/your/new/module/directory

and then make and make install like you normally would. If all goes well, your module will be compiled right in. Nice, huh? No need to muck with the Nginx source, and adding your module to new versions of Nginx is a snap, just use that same ./configure command. By the way, if your module needs any dynamically linked libraries, you can add this to your "config" file:

CORE_LIBS="$CORE_LIBS -lfoo"

Where foo is the library you need. If you make a cool or useful module, be sure to send a note to the Nginx mailing list and share your work.

taxonomy: