precontent阶段

181 阅读1分钟

**
**

一、try_files指令

按照配置的顺序请求文件。try_files指令是ngx_http_try_files_module模块的指令,该模块默认被编译进nginx中,没有办法禁用。

1、指令使用

  • try_files file ...... url
  • try_files file ...... =code

只要有一个file有内容,就立即返回。第一个file不存在,就匹配第二个,以此向后。访问文件的路径是由root或者alias指定的。

2、案例

        location /first {
            root html;
            try_files /test.html /$uri $uri/index.html @lastUrl;
        }

        location @lastUrl {
            return 200 'lasetUrl';
        }

        location /second {
            try_files $uri $uri/index.html $uri.html =404;
        }

当访问http://localhost:8000/first/index.html时,进入first的location中,先匹配/html/test.html,没有找到,则匹配/first/index.html,$uri为/first/index.html,没有则继续向后匹配,如果都没有则跳转到@lastUrl的location中,返回200。

当访问http://localhost:8000/second/index.html时,先匹配/second/index.html,如果没有则向后匹配。$uri为/second/index.html。

二、mirror模块

mirror模块可以实时的拷贝流量,创建一份镜像流量,比如生产环境中我们处理一些请求,这些请求可能需要同步的拷贝一份到测试环境中。

mirror模块默认是编译进nginx中的,可以使用--without-http_mirror_module进行移除。

1、指令使用

  • mirror uri | off:将请求同步复制到uri上。
  • mirror_request_body on | off:是否需要将请求中的 body转发到上游服务中。默认为on。

2、原理

处理请求时,生成一个子请求,访问其他的服务,并且对返回的响应不做处理。

3、案例

启动两个nginx项目,一个nginx-demo,一个nginx-demo1,在nginx-demo中配置:

       location / {
            mirror /mirror;
            mirror_request_body off;
        }

        location = /mirror {
            internal;
            proxy_pass http://local$request_uri;
        }
        

local为nginx-demo1的ip,使用 curl http://localhost:8000/访问nginx-demo的nginx,nginx-demo会产生一个子请求,发送给nginx-demo1的nginx,两个项目的log日志如下:

                                                                    nginx-demo日志

                                                                     nginx-demo1日志