Nginx版本的“helloworld”

Nginx模塊概述

Nginx的模塊不能夠像Apache那樣動態添加,所有的模塊都要預先編譯進Nginx的二進制可執行文件中。
Nginx模塊有三種角色:
(1)Handlers(處理模塊)–用於處理HTTP請求並輸出內容。
(2)Filters(過濾模塊)–用於過濾Headler輸出的內容。
(3)Load-balancers(負載均衡模塊)–當有多臺服務器供選擇時,選擇一臺後端服務器並將HTTP請求轉發到該服務器。

hello world模塊編寫與安裝

(1)執行以下命令,在該目錄內編寫我們的Nginx模塊:
mkdir -p /opt/nginx_hello_world
cd /opt/nginx_hello_world
(2)開始創建nginx模塊所需的配置文件(名爲config)
vim /opt/nginx_hello_world
然後輸入以下內容保存並退出:

ngx_sddon_name=nginx_http_hello_world_module
HTTP_MODULES="$HTTP_MODULES ngx_http_hello_world_module"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_hello_world_module.c"
CORE_LIBS="$CORE_LIBS -lpcre"

(3)創建Nginx的模塊c程序文件(格式爲“ngx_http_模塊名稱_module.c”,本例中爲:ngx_http_hello_world_module.c)
vim /opt/nginx_hello_world/ngx_http_hello_world_module.c

#include <ngx_config.h>
#include<ngx_core.h>
#include<ngx_http.h>

static char *ngx_http_hello_world(ngx_conf_t *cf,ngx_command_t *cmd,void *conf);

static ngx_command_t ngx_http_hello_world_commands[]={
{
ngx_string("hello_world"),
NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
ngx_http_hello_world,
0,
0,
NULL
},
ngx_null_command
};

static u_char ngx_hello_world[]="hello world";
static ngx_http_module_t ngx_http_hello_world_module_ctx ={
NULL,
NULL,

NULL,
NULL,

NULL,
NULL,

NULL,
NULL
};
ngx_module_t ngx_http_hello_world_module ={
NGX_MODULE_V1,
&ngx_http_hello_world_module_ctx,
ngx_http_hello_world_commands,
NGX_HTTP_MODULE,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NGX_MODULE_V1_PADDING
};

static ngx_int_t ngx_http_hello_world_handler(ngx_http_request_t *r)
{
ngx_buf_t *b;
ngx_chain_t out;

r->headers_out.content_type.len = sizeof("text/plain") - 1;
r->headers_out.content_type.data = (u_char *)"text/plain" ;

b= ngx_pcalloc(r->pool,sizeof(ngx_buf_t));

out.buf =b;
out.next =NULL;

b->pos=ngx_hello_world;
b->last =ngx_hello_world +sizeof(ngx_hello_world);
b->memory =1;
b->last_buf =1;

r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n =sizeof(ngx_hello_world);
ngx_http_send_header(r);

return ngx_http_output_filter(r,&out);
}
static char *ngx_http_hello_world(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_world_handler;
return NGX_CONF_OK;

}

(4)參考我的nginx安裝那一篇Nginx安裝博客在這一步稍有不同
**./configure –prefix=/usr/local/nginx –add-module=/opt/nginx_hello_world
make&&make install**
(5)配置nginx.conf(/usr/local/nginx/conf/nginx.conf),在server部分增加以下內容:
**location = /hello{
hello_world;
}**
(6)啓動Nginx,(Nginx的啓動),用瀏覽器訪問http://localhost/hello,就可以看到編寫的Nginx Hello World 模塊輸出的文字“hello world”。

下篇寫代碼分析

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章