Writing a custom Nginx module – Sample Hello World Module

If you want to write a custom Nginx module, Emiller’s guide is a very good starting point. This article is a wee bit long and you might want to get your hands dirty just to see a full program. In this case you can find this hello world module useful.

I found both of them useful, but the hello world program was  simplistic enough for me to miss some concepts, so i wrote this improved hello word module.

Instead of printing “Hello World!”, it will take the argument of what to print. if you provide an empty argument or no argument it will throw an error.  I felt this demonstrated the Nginx module directives a little better, it demonstrates how to validate their value, and i also introduced a post configuration init function to actually assign the handler of the directive. This i think provides a little better modularisation, and just shows the concept of location conf struct which was missing from the original hello world.

The bare-bones process of creating an Nginx module is like below

  1. Create module configuration struct either for location , main or server each with a specific naming convention (see ngx_http_hello_loc_conf_t)
  2. The allowed directives of the module are in a static array of type ngx_command_t (see ngx_http_hello_commands), This will also have the functions pointers which will have the code to validate the value of each directive as well as initialise the handler
  3. Create a module context struct like ngx_http_<module name>_module_ctx of type ngx_http_module_t which has a bunch of hooks for setting up configuration. Here you can have the postconfiguration hook for example to setup the main handler of your module (see ngx_http_hello_module_ctx)
  4. Then we do the module definition which is also a struct of type ngx_module_t and contains references to the module context and module commands, that you created in the steps above (see ngx_http_hello_module)

A sample configuration for the module could look like

server {
listen 8080;
server_name localhost;

location / {
hello 'Hello World';
  }
}

Good Luck with writing an Nginx module, you can download the improved hello world module here

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s