Ubuntu 下apache2 增长新的module

http://andrew913.iteye.com/blog/398648html

 

首先来介绍下apache的一个工具apxs。apxs是一个为Apache HTTP服务器编译和安装扩展模块的工具,用于编译一个或多个源程序或目标代码文件为动态共享对象,使之能够用由mod_so提供的LoadModule指令在运行时加载到Apache服务器中。 apache

 

注意在Ubuntu apache2下 apxs为apxs2,另外非源码包安装的apache2 是不带有apxs2 的。服务器

解决办法:
apt-get install apache2-prefork-dev


1.apxs -g -n helloworld 

上面的命令能够帮助咱们产生一个模块名字为helloworld的模板。 
上面的命令会产生如下代码 函数

#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "ap_config.h"

/* The sample content handler */
static int helloworld_handler(request_rec *r)
{
    if (strcmp(r->handler, "helloworld")) {
        return DECLINED;
    }
    r->content_type = "text/html";      

    if (!r->header_only)
        ap_rputs("The sample page from mod_helloworld.c\n", r);
    return OK;
}

static void helloworld_register_hooks(apr_pool_t *p)
{
    ap_hook_handler(helloworld_handler, NULL, NULL, APR_HOOK_MIDDLE);
}
/* Dispatch list for API hooks */
module AP_MODULE_DECLARE_DATA helloworld_module = {
    STANDARD20_MODULE_STUFF, //用于编译后的模块产生版本信息
    NULL,                  /* 建立目录配置结构*/
    NULL,                  /* 合并目录配置结构 */
    NULL,                  /* 建立主机配置结构 */
    NULL,                  /* 合并主机配置结构 */
    NULL,                  /* 为模块配置相关指令       */
    helloworld_register_hooks  /* 注册模块的钩子函数                      */
};

咱们来看下helloworld_module这个结构体,它没个成员的具体做用请看注释。 
它最关键的参数为最后一个,这个参数是一个注册钩子函数指针,也就是说当咱们把模块加入到apache里面去的时候,他会执行这个注册函数。在这个函数里面咱们将会注册咱们所要添加的钩子。 
本例子中咱们用的是 工具

ap_hook_handler(helloworld_handler, NULL, NULL, APR_HOOK_MIDDLE);  

这个处理函数,这个处理函数注册了helloworld_handler这个函数。这个函数用于处理咱们的请求。 
咱们来说下执行的顺序,模块加载-》执行helloworld_register_hooks函数-》注册helloworld_handler这个函数到钩子上去。 
这样一来:当一个http请求来的时候,咱们就会自动去执行helloworld_handler这个函数。本例子是一个很是简单的内容生成器。 spa

if (strcmp(r->handler, "helloworld")) {//判断是不是这个helloworld  handler
        return DECLINED;//
    }
    r->content_type = "text/html";      
    if (!r->header_only)
        ap_rputs("The sample page from mod_helloworld.c\n", r);//内容生成
    return OK;

下面咱们未来进行编译 
执行:apxs -c mod_helloworld.c 
执行成功之后咱们能够发如今.libs下面会出现mod_helloworld.so这个模块文件。这就是咱们所须要的,对于apache一些自带的模块通常都放在安装目录的modules/下面。 

下面咱们来对其进行配置 
打开httpd.conf文件,添加如下信息 指针

LoadModule helloworld_module   *****// 指定.so文件的路径。

<Location /helloworld>
    setHandler helloworld
</Location>

Ok ,重启apache 而后输入 http://loacalhost/helloworld 就能够看到 
The sample page from mod_helloworld.c 

固然这里这里只是输出一句话,咱们也能够打印不少html信息,就相似于servlet同样。 

这样一来一个简单的apache内容生成器模块已经开发好了,固然应用比较普遍的是过滤器模块的开发,最近项目主要也是用过滤器来实现的。 rest

 

Ubuntu apache2下默认的模块都在 /usr/lib/apache2/modules/下面,code

 

重启apache时,须要sudo  /etc/init.d/apache2 restart,才能成功,不然会出现错误htm

相关文章
相关标签/搜索