Linux under Nginx custom module development __linux

Source: Internet
Author: User

Nginx is a powerful server, it can deploy high-performance cluster, it allows engineers to write their own functional modules, recommend the reader in the preparation of their own functional modules, before the Nginx to a more comprehensive understanding. Share a better network disk link: Https://pan.baidu.com/s/1hs26ZZY


introduce the background of the functional modules I wrote:

This is a function module that can monitor the user's access to our interface through Nginx. Because the actual part is more complex, the code is bigger, now this shows the simplified function, when the user accesses a specific URL, Nginx can capture this URL through this function module, and to parse, Determine if the user's request should be answered. This is not a very careful description of what the code is meant to represent. Because it involves a lot of content, including Nginx's basic data structure, and so on.


The first thing to note is 1:

Download and install. Nginx window version and Linux version, the window version of the Nginx basically can not be extended. But the direct decompression can be used, also do not need to install dependencies, so it is the "tool." Linux version can not be used directly, is a bunch of source code, so there is a "installation" process, but it is because of this, it allows engineers to write their own modules, and then with the original module compiled into tools.

The Linux version of the Nginx source code compilation and as a tool of the nature is separate, meaning that the nginx source can be compiled countless times, but as a tool as long as the installation can be, straight point of view, is in the Linux system, the source code in a folder A, And the nginx you need to start is in another folder B. When a new module needs to be added, you need to compile your own Nginx code (folder a), generate a new Nginx launcher, and then replace the Nginx in folder B, the first time you compile the installation to refer to http://blog.csdn.net/ c1481118216/article/details/77132149.

$ sudo apt-get install gcc zlib1g-dev libpcre3 libpcre3-dev libssl-dev//Download Dependency pack

wget https://nginx.org/download/nginx-1.13.4.tar.gz//Download the latest version of Nginx $ TAR-XVF nginx-1.13. 4. tar.gz$ CD nginx-1.13. 4///Decompression


Compilation and installation, the first two steps are compiled, and the last step is to install

$./configure

$sudo make

$sudo make Install

Nginx installed, there will be two places related to Nginx, the first place is under/home/, is our first download and extract the place, see the following files, it is the source code.


The second place is under/usr/local, there is a Nginx folder, compile and install good nginx right here. We usually start Nginx is to locate here.




In fact Nginx has been installed, we started to write our own module

issues to be aware of 2

First of all, we write a module on what exactly corresponds to Nginx, first look at the following figure, This is the Nginx configuration file Nginx.conf,nginx is the file to add the Nginx function, the added here is not to write a new function module, but will NIGNX already have the switch on the function module open, we will write the function in the compiled after the configuration, can be used. What we call a custom module is the equivalent of the server in the image below, or listen, or server_name, (our monitor), and the Monitor's function is not available in Nginx itself, but when we go through a process, We can add things like Minitor Mysecreepassword in this file to handle the user's request.



Start writing your own module

To write your own functional modules, you need to write two files, one for Ngx_[module_type]_[self_definition_name]_module.c and config two files.

Based on Nginx development of custom modules, the use of file names, is a regular, for example: the following laws

NGX is fixed.

Module_type is an existing module in Nginx, at compile time, Nginx determines which class your module should be classified by identifying the segment.

Self_definition_name is Custom, Nginx identifies this segment to determine your instructions in nginx.conf, such as monitor, so write in nginx.conf

Monitor XXXXXXXX on behalf of our module.

Here's what ngx_http_monitor_module.c.

#include <ngx_config.h>//the packages of nginx #include <ngx_core.h> #include <ngx_http.h> static voi
D *ngx_http_monitor_create_loc_conf (ngx_conf_t *CF);
Static char * Ngx_http_monitor (ngx_conf_t *cf, ngx_command_t *cmd, void *conf);



Static ngx_int_t Ngx_http_monitor_handler (ngx_http_request_t *r);



typedef struct {ngx_str_t secret;} ngx_http_monitor_conf_t; Static ngx_command_t ngx_http_monitor_commands[] = {ngx_string ("monitor"), ngx_http_loc_conf |





Ngx_conf_take1, Ngx_http_monitor, Ngx_http_loc_conf_offset, 0, NULL,}, Ngx_null_command}; Static ngx_http_module_t Ngx_http_monitor_module_ctx = {null, NULL, NULL, NULL, NULL, NULL, ngx_http_monitor_creat





E_loc_conf, NULL};
	ngx_module_t Ngx_http_monitor_module = {ngx_module_v1, &ngx_http_monitor_module_ctx, Ngx_http_monitor_commands,


Ngx_http_module, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ngx_module_v1_padding}; static void *ngx_http_monitor_creaTe_loc_conf (ngx_conf_t *cf) {ngx_http_monitor_conf_t * MYCF;
	MYCF = Ngx_palloc (cf->pool, sizeof (ngx_http_monitor_conf_t));
	if (MYCF = = NULL) {return ngx_conf_error;
	} mycf->secret.len = 0;
	Mycf->secret.data = NULL;
return MYCF;
	Static char * Ngx_http_monitor (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_monitor_handler;
	Ngx_conf_set_str_slot (cf, CMD, conf);
return NGX_CONF_OK; The static ngx_int_t Ngx_http_monitor_handler (ngx_http_request_t *r) {if (!) ( R->method & (Ngx_http_get |
    Ngx_http_head)) {return ngx_http_not_allowed;
    } ngx_int_t rc = Ngx_http_discard_request_body (r);
    if (RC!= ngx_ok) {return rc;
    } ngx_http_monitor_conf_t *MYCF;
    MYCF = ngx_http_get_module_loc_conf (R, Ngx_http_monitor_module);
    ngx_int_t Isauth = 0;
    ngx_str_t format = ngx_string ("Secret=%v"); Ngx_str_t match;
    Match.len = format.len-2 + mycf->secret.len;
    Match.data = Ngx_palloc (R->pool, Match.len);
    ngx_snprintf (Match.data, Match.len, "Secret=%v", &mycf->secret);
    ngx_uint_t i = 0; if (R->args.len >= Match.len) {for (; I <= r->args.len-match.len; i++) {if (0 = ngx_strncasecmp (r-& Gt;args.data + I, Match.data, Match.len)) {if (I < r->args.len-match.len && * (r->args.data + i + mat
		Ch.len)!= ' & ') {continue;
		} if (i!= 0 && * (r->args.data + i-1)!= ' & ') {continue;
			} Isauth = 1;
		Break
	}} ngx_str_t response;

	if (Isauth = = 1) {Ngx_str_set (&response, "secret Right");
	else {ngx_str_set (&response, "secret wrong");
	} ngx_str_t type = ngx_string ("Text/plain");
	R->headers_out.status = NGX_HTTP_OK;
	R->headers_out.content_length_n = Response.len;
	R->headers_out.content_type = type;
	rc = Ngx_http_send_header (r); if (rc = = Ngx_errOR | | RC > Ngx_ok | |
	r->header_only) {return rc;
	} ngx_buf_t *b;
	b = Ngx_create_temp_buf (R->pool, Response.len);

	if (b = = NULL) {return ngx_http_internal_server_error;
	} ngx_memcpy (B->pos, Response.data, Response.len);
	B->last = B->pos + Response.len;
	B->last_buf = 1;
	Ngx_chain_t out;
	Out.buf = b;
	Out.next = NULL;
Return Ngx_http_output_filter (R, &out); }


Then the conf file, conf file content is relatively simple

Ngx_addon_name=ngx_http_monitor_module

http_modules= "$HTTP _modules ngx_http_monitor_module"

NGX_ADDON_ srcs= "$NGX _addon_srcs $ngx _addon_dir/ngx_http_monitor_module.c"

These two files are placed under the Ngx_http_monitor_module folder.


Once the two files are ready, we navigate to the Nginx source folder and execute

./configure--add-module=/usr/adtmodule/ngx_http_monitor_module

Then Nginx will start compiling your module, and after compiling,

Execute make

Issues to be aware of 3

Note that you cannot perform make install at this point because you already have a nginx installed. Then after make, in the Objs folder will have a nginx, will this nginx replace the original/usr/local/nginx/sbin/under that nginx. At this point our new module has been written and installed, how to use it, open/usr/local/nginx/conf/nginx.conf, and then configure the following information


Location =/monitor {
            # only pass the secret parameter value is secretpassword by validating
            # 1 displays ' Secret right ' # 2 through the validation page
            ' without verifying the page display ' Secret wrong "
            # like
            # Http://localhost:8080?monitor=secretpassword through
            # http://localhost:8080?monitor= 123 does not pass
            monitor Secretpassword;
        }

Then start Nginx.

Test, we can get the following results




At this point, the custom module of the compilation and installation of the end, is not very simple.




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: info-contact@alibabacloud.com 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.