u_char*ngx_http_map_uri_to_path(ngx_http_request_t*r,ngx_str_t*path,size_t*root_length,size_treserved){u_char*last;size_talias;ngx_http_core_loc_conf_t*clcf;clcf=ngx_http_get_module_loc_conf(r,ngx_http_core_module);alias=clcf->alias;if(alias&&!r->valid_location){ngx_log_error(NGX_LOG_ALERT,r->connection->log,0,"\"alias\" cannot be used in location \"%V\" ""where URI was rewritten",&clcf->name);returnNULL;}if(clcf->root_lengths==NULL){*root_length=clcf->root.len;path->len=clcf->root.len+reserved+r->uri.len-alias+1;path->data=ngx_pnalloc(r->pool,path->len);if(path->data==NULL){returnNULL;}last=ngx_copy(path->data,clcf->root.data,clcf->root.len);}else{if(alias==NGX_MAX_SIZE_T_VALUE){reserved+=r->add_uri_to_alias?r->uri.len+1:1;}else{reserved+=r->uri.len-alias+1;}if(ngx_http_script_run(r,path,clcf->root_lengths->elts,reserved,clcf->root_values->elts)==NULL){returnNULL;}if(ngx_get_full_name(r->pool,(ngx_str_t*)&ngx_cycle->prefix,path)!=NGX_OK){returnNULL;}*root_length=path->len-reserved;last=path->data+*root_length;if(alias==NGX_MAX_SIZE_T_VALUE){if(!r->add_uri_to_alias){*last='\0';returnlast;}alias=0;}}last=ngx_copy(last,r->uri.data+alias,r->uri.len-alias);*last='\0';returnlast;}
获取当前请求所匹配 location 的 HTTP 核心模块配置, 将配置中的 alias 值赋给局部变量 alias
3 安全检查
if(alias&&!r->valid_location){ngx_log_error(NGX_LOG_ALERT,r->connection->log,0,"\"alias\" cannot be used in location \"%V\" ""where URI was rewritten",&clcf->name);returnNULL;}
alias:局部变量,其值来自 clcf->alias。当 location 配置了 alias 指令时,该值为非零 r->valid_location:请求中的一个标志位。 初始为 1,表示当前 location 配置有效。 如果在 rewrite 阶段修改了 URI,该标志会被置为 0 当同时满足“使用了 alias”且“location 有效性已被破坏(URI 被改写)”时进入分支 alias 的工作原理是将 location 前缀直接替换为指定的文件系统路径, 这种映射强依赖于请求 URI 与 location 的匹配关系。 一旦 URI 被 rewrite 修改,原始 location 的匹配结果就可能不再准确, 若继续使用 alias 进行路径拼接,很可能构造出错误的文件路径