nginx的try_files指令

12,759 阅读1分钟
try_files指令
语法:try_files file ... uri 或 try_files file ... = code
默认值:无
作用域:server location

作用是按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜杠/的表示文件夹),若所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。

需要注意的是,只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向。
最后一个参数是回退URI且必须存在,否则会出现内部500错误。
命令的location也可以用在最后一个参数中。
与rewrite指令不同,如果回退URI不是命名的location那么$args不会自动保留,如果你想保留$args,则必须明确声明。

try_files $uri $uri/ /index.php?q=$uri&$args;

示例一

try_files 将尝试你列出的文件并设置内部文件指向。

try_files static/ $uri @fallback;
index index.html index.php;

依次检测$root/static/index.html,$root/static/index.php,$root/$uri是否存在,若不存在则重定向到@fallback。

也可以使用一个文件或者状态码(=404)作为最后一个参数,如果最后一个参数是文件,那么这个文件必须存在。

示例二

try_files 跳转到变量

server {
    listen 8080;
    server 127.0.0.1;
    root html;
    index index.html index.htm;
    
    location /abc {
        try_files /1.html /2.html @qwe;
    }
    
    location @qwe {
        rewrite ^/(.*)$ www.baidu.com;  # 跳转到百度页面
    }
}

访问/abc时,若没有检测到1.html和2.html存在,则去查找@qwe

示例三

try_files 跳转到后端upstream

upstream ops-system {
    server 127.0.0.1:28080;
}

server {
    listen 8080;
    server www.abc.com;
    root /data/deploy/abc/;
    index index.html index.htm;
    try_files $uri @ops;
    
    location @ops {
        proxy_pass http://ops-system;
    }
}

其它

try_files 指令可以解决vue或react框架的history路由模式报404或500问题。

location /message {
        alias   /data/www/u-learning-message/develop/dist/;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html =404;
    }