您的位置:首页 > 理论基础 > 计算机网络

nginx代码分析-http模块-access

2013-11-07 11:08 316 查看
版本 : 1.5.5
代码:http/modules/ngx_http_access_module.c
模块作用: 对定义的virtual server与location进行访问控制
配置方法:可以配置在http{} 中的main, srv, loc 3个级别的任意位置进行配置, 如
http{
    deny 192.168.0.1;  // 所有server不允许该源IP访问
    server{
       deny 192.168.0.2;  // 该server不许该IP访问
       location /a { allow 127.0.0.1; deny all ;}  // 只允许本机访问
       location /b { allow all ; }
    }
}

相关数据结构
typedef struct {    /* 代表对一条对CIDR地址的处理规则 */
    in_addr_t         mask;
    in_addr_t         addr;
    ngx_uint_t        deny;      /* unsigned  deny:1; */
} ngx_http_access_rule_t;
typedef struct {     /* access模块的自定义配置结构体, 与conf文件中的配置对应, rules动态数组记录了所有规则*/
    ngx_array_t      *rules;     /* array of ngx_http_access_rule_t */
#if (NGX_HAVE_INET6)
    ngx_array_t      *rules6;    /* array of ngx_http_access_rule6_t */
#endif
} ngx_http_access_loc_conf_t;

static char *
ngx_http_access_rule(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
配置文件解析阶段, ngx_conf_parse函数解析配置文件时, 读到deny, allow两个指令时调用函数 ngx_http_access_rule.
1. 解析第2个参数地址为自定义CIDR结构ngx_cidr_t, 根据deny or allow生成一条ngx_http_access_rule_t规则
2. 如果第2个参数,为all 则cidr.u.in.mask == 0, cidr.u.in.addr == 0, ngx_http_access_loc_conf_t->rules添加第1步该CIDR生成一条处理规则
static void *
ngx_http_access_create_loc_conf(ngx_conf_t *cf)
static char *
ngx_http_access_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
access模块对应的location级别配置的生成和合并函数, 每个server对应的ngx_http_ctx_t->loc_conf[i] (i是access模块在http类模块中的索引号) 指向该server的ngx_http_access_loca_conf_t配置.
static ngx_int_t
ngx_http_access_init(ngx_conf_t *cf)
http模块的postconfiguration函数指针, 解析完配置文件后, 将http core main conf的NGX_HTTP_ACCESS_PHASE阶段处理函数设置为ngx_http_access_handler
static ngx_int_t
ngx_http_access_handler(ngx_http_request_t *r)
1. 将request源IP转为CIDR->IP,
2. 交ngx_http_access_inet判断, 遍历ngx_http_access_loc_conf_t比较
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: