您的位置:首页 > 运维架构 > Nginx

[nginx] 脚本引擎

2017-02-10 13:10 204 查看
配置文件中变量的使用:Nginx 变量漫谈

代码注释:Nginx 脚本引擎解析源码注释

一、普通变量

./src/http/ngx_http_core_module.h
struct 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获取变量的值。每条请求处理时:

ngx_http_create_request
里会对
ngx_http_request_t *r
variables
申请与上面
variables
同长度的数组,用来存放对应变量的值;

执行
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指令剖析
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nginx