Nginx之 try_files 指令

location / {
            try_files $uri $uri/ /index.php;
}

当用户请求 http://localhost/example 时,这里的 $uri 就是 /example。
try_files 会到硬盘里尝试找这个文件。如果存在名为 /$root/example(其中 $root 是项目代码安装目录)的文件,就直接把这个文件的内容发送给用户。
显然,目录中没有叫 example 的文件。然后就看 $uri/,增加了一个 /,也就是看有没有名为 /$root/example/ 的目录。
又找不到,就会 fall back 到 try_files 的最后一个选项 /index.php,发起一个内部 “子请求”,也就是相当于 nginx 发起一个 HTTP 请求到 http://localhost/index.php。

-----------------------------------------------------------------------------------------------------------

try_files 指令作用于(server 和 location 上下文)用于按序检测文件是否存在,并返回第一个找到的文件。

server {
    root /www/nginx;
    index index.html index.jsp;

    charset utf-8;
    access_log /var/log/nginx/host.access.log main;
    error_log /var/log/nginx/host.error.log error;

    location ^~ /test/ {
        index index.html;
        try_files /2.html /1.html /test/test2.html @bd;
    }

    location @bd {
        rewrite ^/(.*)$ http://www.google.com;
    }
}

/ 表示 root 所在的目录,1.html 文件前需添加 /,否则请求的格式为 /www/nginx1.html。

以 /test/ 开头的 URL 将会匹配 location ^~ /test/ { ... },然后 try_files 指令会分别查找 /www/nginx/2.html、/www/nginx/1.html、/test/test2.html 以及 @bd。

若前三个 HTML 文件均不存在,则会匹配(内部重定向) location @bd { ... }。

猜你喜欢

转载自www.cnblogs.com/wjoyxt/p/10366156.html