[nginx] 脚本引擎

来源:互联网 发布:学信网通知单编号 编辑:程序博客网 时间:2024/06/04 18:00
  • 配置文件中变量的使用:Nginx 变量漫谈
  • 代码注释:Nginx 脚本引擎解析源码注释

一、普通变量

./src/http/ngx_http_core_module.hstruct ngx_http_core_main_conf_t {    ngx_hash_t variables_hash;    ngx_hash_keys_arrays_t *variables_keys;  // variables_hash的前身,所有变量先装载到这里,然后再构造出variables_hash    ngx_array_t variables;};

nginx变量大体上分为内部变量和外部变量:

  • 内部变量,包括./src/http/ngx_http_variables.c定义的ngx_http_core_variables,主要是相对于外部变量
  • 外部变量,配置文件中set $var value定义的变量

所有定义变量都要放到variables_keys中,而只有使用到的变量(如配置文件中出现过的)才会放到variables里,并把index保存到hash表,便于用变量名检索到index,后面用index获取变量的值。每条请求处理时:

  1. ngx_http_create_request里会对ngx_http_request_t *rvariables申请与上面variables同长度的数组,用来存放对应变量的值;
  2. 执行ngx_http_rewrite_handler,会执行脚本引擎的指令数组codes,每条指令返回的数据都是压栈到sp中,下一条指令则从sp中出栈拿到数据:
    • set $var const,若是常量字符串赋值,两条指令,const就在第一条codes指令结构中,弹出到下一条指令;
    • set $var_other $var,若是变量赋值,也是两条指令,但第一条为复杂指令,其中又包含两条指令,分别为获取变量长度(用于申请内存)和变量值,再弹出到下一条指令
    • 补充:若内部变量设置了set_handler,比如$args,变量值是放在ngx_http_request_t.args,而不放到variables

二、特殊变量

指未收录到ngx_http_core_variables的变量,包括:

变量前缀 意义 解析方法 arg_ 请求的URL参数 ngx_http_variable_argument http_ 请求中的HTTP头部 ngx_http_variable_unknown_header_in sent_http_ 发送响应中的HTTP头部 ngx_http_variable_unknown_header_out cookie_ Cookie头部中的某个项 ngx_http_variable_cookie upstream_http_ 后端服务器HTTP响应头部 ngx_http_upstream_header_variable

这里变量都是在ngx_http_variable_init_vars()绑定get_handler

三、Rewrite模块指令

nginx rewrite 指令

  • set,定义变量并赋值,有“弱”作用域概念
  • if,会生成location添加到本block的locations队列,支持=、!=、~、~*、!~、!~*等,参见nginx rewrite if指令剖析
0 0