数据库教程:nginx对http请求处理的各个阶段详析

在编写nginx的http的模块的时候,需要在各个阶段对http请求做相应的处理,以达到不同的目的,比如请求发起的时候是否有访问权限、内容生成的时候进行过滤或者其它处理等等。如果在编译nginx模块内

在编写nginx的http的模块的时候,需要在各个阶段对http请求做相应的处理,以达到不同的目的,比如请求发起的时候是否有访问权限、内容生成的时候进行过滤或者其它处理等等。如果在编译nginx模块内注册的处理阶段不正确会导致达不到想要的结果,比如你想处理内容的时候内容实际上这个时候是没有的,如此等等。

在nginx内部定义了多个阶段的类型以满足不同的处理要求(ngx_http_core_module.h中,不同版本不一样):

  typedef enum {   ngx_http_post_read_phase = 0,      ngx_http_server_rewrite_phase,      ngx_http_find_config_phase,   ngx_http_rewrite_phase,   ngx_http_post_rewrite_phase,      ngx_http_preaccess_phase,      ngx_http_access_phase,   ngx_http_post_access_phase,      ngx_http_try_files_phase,   ngx_http_content_phase,      ngx_http_log_phase  } ngx_http_phases;  

各对应的意思分别为:

  ngx_http_post_read_phase = 0  //读取请求阶段  ngx_http_server_rewrite_phase //uri转换阶段  ngx_http_find_config_phase   //查找相应的配置来执行阶段  ngx_http_rewrite_phase    //uri转换阶段(不太清楚此处)  ngx_http_post_rewrite_phase  //对转换后的url结果进行处理的阶段  ngx_http_preaccess_phase   //权限检查准备阶段  ngx_http_access_phase    //权限检查阶段  ngx_http_post_access_phase  //对权限检查结果进行处理阶段  ngx_http_try_files_phase   //处理配置中的try_files阶段  ngx_http_content_phase    //处理生成返回数据阶段(此处认为不太细,当然有filter也可以忽略)  ngx_http_log_phase     //记录日志处理阶段,具体说明应当是请求完成后,关闭请求时处理  

从这个配置中可以分析出来nginx在处理请求的整个流程,流程是从头执行到尾的,可见log是放在最后面执行,对于内容段的处理一般都是在filter模块中去做,在ngx_http_log_phase阶段注册的处理段也不能获取到返回的数据,返回数据在发送至客户端后就直接给释放了。因此,在各个阶段处理时应当清楚这个阶段的数据准备情况。

正常情况下,我们可以通过如下的方式来注册我们自己的处理模块:

  static ngx_int_t  ngx_http_xxx_init(ngx_conf_t *cf)  {   ngx_http_handler_pt  *h;   ngx_http_core_main_conf_t *cmcf;      cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);      h = ngx_array_push(&cmcf->phases[ngx_http_content_phase].handlers);   if (h == null) {   return ngx_error;   }      *h = ngx_http_xxx_handler;      return ngx_ok;  }  

且ngx_http_xxx_up_handler的返回值只能是如下几个:

  ngx_ok        //处理成功,进入下一阶段  ngx_declined      //放弃处理  ngx_again || ngx_done  //处理完成,返回该值会触发请求  ngx_error || ngx_http_.. //处理错误或者http的其它状态值  

另外对于ngx_http_content_phase阶段,实际上还有另外一种注册方式,just like this:

  static char *  ngx_http_xxx_server(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)  {   ngx_str_t     *value;   ngx_url_t     u;   ngx_http_core_loc_conf_t *clcf;      clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);      clcf->handler = ngx_http_xxx_handler;      if (clcf->name.data[clcf->name.len - 1] == '/') {   clcf->auto_redirect = 1;   }      return ngx_conf_ok;  }  

不过这样子,你要做的东西就太多了,更多的情况下考虑下upstream结合或者对请求进行特殊处理,比如对于分布式存储的分发,需要对请求处理和文件系统关联时、比如请求的数据直接交给特殊的server来拿内容时。呵呵.

到此这篇关于nginx对http请求处理的各个阶段详析的文章就介绍到这了,更多相关nginx对http请求处理详析内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!

需要了解更多数据库技术:nginx对http请求处理的各个阶段详析,都可以关注数据库技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/dtteaching/813251.html

(0)
上一篇 2021年9月14日
下一篇 2021年9月14日

精彩推荐