Nginx Learning (2) Hello World Program

Source: Internet
Author: User

Hello wrold

1 program

2 implementation steps


2.2 module code implementation

2.3 compile the configuration file

3. Compile the module into nginx

1 Purpose of this section

This section uses nginx to implement a classic program "Hello world". This program is the first program we come into contact with when learning any programming language. The purpose of this program is

A preliminary understanding of how to embed nginx into a third-party module is also an entry to the nginx HTTP module.

2 implementation steps

Nginx provides a simple way to embed a third-party module into nginx: only three steps are required.

Step 1: Compile config

Step 2: implement the module code

Step 3: modify the configuration parameters and compile a third-party module into nginx

Next we will use the simplest Hello World instance to illustrate the implementation of these three steps.


The config file contains three parameters:

Ngx_addon_name: name of a third-party module. this parameter is generally set to the module name.

Http_modules: htpp Module name

Ngx_addon_srcs: source code path of a third-party module

Below is the config of the helloworld program:

ngx_add_name=ngx_http_hello_moduleHTTP_MODULES="$HTTP_MODULES ngx_http_hello_module"NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_hello_module.c"

2.2 module code implementation

The following describes how to implement ngx_http_hello_module.c.

First, we need to define two functions:

static char* ngx_http_hello(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);static ngx_int_t ngx_http_hello_handler(ngx_http_request_t *r);

This function is used to analyze the parameters in the configuration file. Because we only need to output Hello world, we use a configuration without parameters, that is, we do not need to parse the parameter values, in the next section, I will detail how to analyze the configuration parameters.

Each module has a handler function that processes requests from the client. To process this function, you can either directly generate the content on your own, or reject the processing, which will be processed by the subsequent handler, or be discarded to the subsequent filter for processing.

Then we need to define three structs, which are essential for each module:

Module configuration command structure:

static ngx_command_t ngx_http_hello_commands[] = {    {       ngx_string("test_hello"),       NGX_HTTP_LOC_CONF | NGX_CONF_NOARGS,       ngx_http_hello,       NGX_HTTP_LOC_CONF_OFFSET,       0,       NULL    },    ngx_null_command};
Module Context Structure:

static ngx_http_module_t ngx_http_hello_module_ctx = {    NULL,    NULL,    NULL,    NULL,        NULL,    NULL,    NULL,    NULL,};
Definition struct of the module:

ngx_module_t ngx_http_hello_module = {    NGX_MODULE_V1,    &ngx_http_hello_module_ctx,    ngx_http_hello_commands,    NGX_HTTP_MODULE,    NULL,    NULL,    NULL,    NULL,    NULL,    NULL,    NULL,    NGX_MODULE_V1_PADDING};
Here we only know the three structs. We will introduce them in detail later.

Then let's look at the implementation of the nginx function:

static char* ngx_http_hello(ngx_conf_t *cf, ngx_command_t *cmd, void *conf){    ngx_http_core_loc_conf_t *clcf;    clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);    clcf->handler = ngx_http_hello_handler;    return NGX_CONF_OK;}
This function is mainly used to parse the configuration parameters. You can also set the handler function of the module. Here we do not parse the configuration parameters. We only load the handler function of the module.

Let's look at the handler function that actually processes user requests:

static ngx_int_t ngx_http_hello_handler(ngx_http_request_t *r){    if (!(r->method & (NGX_HTTP_HEAD | NGX_HTTP_GET)))     {       return NGX_HTTP_NOT_ALLOWED;    }    ngx_int_t rc = ngx_http_discard_request_body(r);    if (rc != NGX_OK)    {       return rc;    }        ngx_str_t type = ngx_string("text/html");    ngx_str_t response = ngx_string("hello world!");    r->headers_out.content_type = type;    r->headers_out.status = NGX_HTTP_OK;    r->headers_out.content_length_n = response.len;    if (r->method == NGX_HTTP_HEAD)    {       return ngx_http_send_header(r);    }        ngx_buf_t* buf = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));    if (buf == NULL)    {       return NGX_HTTP_INTERNAL_SERVER_ERROR;    }    buf->pos = ngx_pcalloc(r->pool, response.len);    buf->last = buf->pos + response.len;    buf->last_buf = 1;    buf->memory = 1;    ngx_memcpy(buf->pos,, response.len);        ngx_chain_t out;    out.buf = buf; = NULL;    rc = ngx_http_send_header(r);    if (rc == NGX_ERROR || rc > NGX_OK || r->header_only)    {       return rc;    }    return ngx_http_output_filter(r, &out);}
This function is a function that truly processes user requests. After parsing the configuration parameters, it processes the user requests accordingly and returns the processing results to the user.

The Code of such a simple hello module is basically complete. In fact, it is mainly the definition of the three struct above and the implementation of the handler function.

2.3 compile the configuration file

When we enter localhost/hello and press enter, we will see: Hello world!

In the configuration, there should be hello and written in the location of nginx. conf:

Location/Hello {test_hello; // configuration without parameters}
3. Compile the module into nginx

Install a third-party module as follows:

. /Configure -- prefix =/home/smtl/desktop/testnx/nginx -- with-http_ssl_module -- With-PCRE =/home/smtl/download/pcre-8.33 -- With-zlib =/home/smtl/ download/zlib-1.2.8 -- With-OpenSSL =/home/smtl/download/openssl-0.9.8o <span style = "color: # ff0000; "> -- add-module =/home/smtl/desktop/testnx/nginx-1.0.15/my_hello_module </span>
(Make, make install)

Note that the files written in the code should be placed in the same directory as the nginx source code: The nginx source code should be placed in that file, and the files of the code we wrote should be placed in that file.

The red part is the folder where the code ngx_htttp_hello_module.c is written.

Enter localhost/hello in the browser.

Browser output Hello World

Program source code:

# Include <ngx_config.h> # include <ngx_http.h> # include <ngx_core.h> static char * ngx_http_hello (ngx_conf_t * Cf, ngx_command_t * cmd, void * conf ); static ngx_int_t iterator (iterator * r); static ngx_command_t iterator [] ={{ ngx_string ("test_hello"), ngx_http_loc_conf | delimiter, ngx_http_hello, delimiter, 0, null}, ngx_null_command }; static ngx _ Http_module_t ngx_http_hello_module_ctx = {null, null,};/* Static addition Error */ngx_module_t ngx_http_hello_module = {ngx_module_v1, & amp; dependencies, ngx_http_hello_commands, ngx_http_module, null, ngx_module_v1_padding}; static char * ngx_http_hello (ngx_conf_t * Cf, ngx_command_t * cmd, void * conf) {ngx_http_core_lo C_conf_t * clcf; clcf = forward (CF, ngx_http_core_module); clcf-> handler = forward; return ngx_conf_ OK;} static ngx_int_t forward (ngx_http_request_t * r) {If (! (R-> Method & (ngx_http_head | ngx_http_get) {return ngx_http_not_allowed;} ngx_int_t rc = ngx_http_discard_request_body (r); If (RC! = Ngx_ OK) {return RC;} ngx_str_t type = ngx_string ("text/html"); ngx_str_t response = ngx_string ("Hello world! "); R-> headers_out.content_type = type; r-> headers_out.status = ngx_http_ OK; r-> headers_out.content_length_n = response. len; If (R-> Method = ngx_http_head) {return ngx_http_send_header (r);} ngx_buf_t * Buf = ngx_pcalloc (R-> pool, sizeof (ngx_buf_t )); if (BUF = NULL) {return ngx_http_internal_server_error;} Buf-> Pos = ngx_pcalloc (R-> pool, response. len); Buf-> last = Buf-> POS + response. len; Buf-> last_buf = 1; Buf-> memory = 1; ngx_memcpy (BUF-> POs, response. data, response. len); ngx_chain_t out; out. buf = Buf; out. next = NULL; rc = ngx_http_send_header (r); If (rc = ngx_error | rc> ngx_ OK | r-> header_only) {return RC;} return ngx_http_output_filter (r, & out );}

Nginx Learning (2) Hello World Program

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.