Nginx:rewrite重写模块

一、配置

  1. rewrite目的为“http://”或“https://”:rewrite的handler结束后将直接返回302临时重定向。
  2. last:具有last的一行指令解析结束后,会在codes数组最后填充NULL,所以同一块区域后面的rewrite相关指令都不再生效。
  3. break:r->uri_changed会被赋值为0,在POST_REWRITE阶段,执行r->phase_handler++,从而直接进入下一阶段。break也具有last的结束属性。
  4. redirect:handler结束后直接返回302临时重定向。
  5. permanent:handler结束后直接返回303永久重定性。

二、流程

  1. server_rewrite和location_rewrite的区别
    对于server_rewrite和rewrite两个阶段来说,处理流程几乎无差异。只是code的对象不同,server和location的ngx_http_rewrite_loc_conf_t是两个不同的空间。

    1)在11阶段前,当解析host后,调用ngx_http_set_virtual_server进行server块的查询,并进行如下赋值:

    r->srv_conf = cscf->ctx->srv_conf;
    r->loc_conf = cscf->ctx->loc_conf;

    所以,server_rewrite阶段获取的ngx_http_rewrite_loc_conf_t是属于server块的。

    2)而在location_rewrite前的NGX_HTTP_FIND_CONFIG_PHASE阶段,会进行location块查找,并对r->loc_conf重新赋值,所以此时获取的ngx_http_rewrite_loc_conf_t是属于location块的。

  2. rewrite跳转
    在这里插入图片描述
    1)对于普通的非break、redirect、permanent的rewrite,如果在NGX_HTTP_REWRITE_PHASE命中重定向,那么在NGX_HTTP_POST_REWRITE_PHASE(该阶段ph->next = find_config_index)执行结束后会跳转到NGX_HTTP_FIND_CONFIG_PHASE,进行重定向后的location查找。
    2)对于break的rewrite,命中重定向后不会再返回FIND_CONFIG阶段。
    3)内部重定向阶段跳转:

    a. server_rewrite_index:
    对于r->internal为1并且调用ngx_http_handler重走阶段时,会赋值“r->phase_handler =
    cmcf->phase_engine.server_rewrite_index”,则之后流程跳过POST_READ,直接进入 SERVER_REWRITE阶段。目前两种情况满足上述条件:
    1)所有子请求;
    2)调用ngx_http_internal_redirect函数进行内部重定向。
    例如,post_action字段,为当前完成请求的子请求定义一个URI。

    location /protected_files { 
      	internal;
    	proxy_pass http://127.0.0.2;
    	post_action /protected_done;
    }
    

    例如,index模块,对于首字符为“/”的index,执行内部重定向。 例如,try_files $uri /index.php。

    b. location_rewrite_index:
    对于配置中使用了“@”的重定向,通常会调用ngx_http_named_location的请求,进行重定向uri,查找locaiton块,并赋值“r->phase_handler
    = cmcf->phase_engine.location_rewrite_index”,后续流程跳转到NGX_HTTP_REWRITE_PHASE阶段。 (与其称为rewrite,不如称为foward,不对请求的uri进行修改) 目前满足上述条件的有:
    1)try_files $uri @abc;
    2)error_page 403 @abc;
    3)@开头的x_accel_redirect。

猜你喜欢

转载自blog.csdn.net/u013032097/article/details/91388081