Nginx的try_files使用详解

try_files

语法: try_files file ... uri 或 try_files file ... = code

默认值: 无

作用域: server location

按顺序检查文件是否存在,返回第一个找到的文件。结尾的斜线表示为文件夹 -$uri/。如果所有的文件都找不到,会进行一个内部重定向到最后一个参数。

匹配文件夹下的内容,如果没有转到/index.php

try_files /app/cache/ $uri /index.php;

index index.php index.html;

它将检测$document_root/app/cache/index.php,$document_root/app/cache/index.html 和 $document_root$uri是否存在,

重定向到另外一台服务器示例:(查找目录下是否存在文件,如果不存在转到@new_uploads下,new_uploads对应代理到172.17.0.101上)

location ^~ /uploads/ {
        root /data/weiwend/weiwang;
        try_files $uri @new_uploads;
    }
    
    location @new_uploads {
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://172.17.0.101:80;
    }

返回状态码

try_files /app/cache/ $uri =500;;

index index.php index.html;

备注:这个函数试试会进行内部重定向,可以和 deny 等配合使用(rewrite 等如果和deny一起使用将没有效果)

原文地址:https://www.cnblogs.com/fishbook/p/9679516.html