try_files $uri $uri/ /index.html;

1. 语法介绍

# 1.假设请求 127.0.0.1/home

# 2.nginx配置的location
location / {
    root   /opt/dist;
    index  index.html;
    try_files $uri $uri/ /index.html;
    }


# 变量解释
try_files  固定语法
$uri       指代home文件(ip地址后面的路径,假如是127.0.0.1/index/a.png,那就指代index/a.png)
$uri/      指代home文件夹
/index.html  向ip/index.html 地址发起请求


try_files $uri $uri/ /index.html;
尝试解析下列2个文件/文件夹(自动分辨出,IP后面的路径是文件还是文件夹), $uri/$uri/,
如果解析到,返回第一个,
如果都没有解析到,向127.0.0.1/index.html发起请求跳转(该路由必须真实,不然会报错)

2. 其他用法

2.1 实现内部跳转新的location 

server {
 listen 8000;
 server_name 127.0.0.1;
 
 
 location / {
     root html;
     index index.html;
     # 检测根目录下文件4.html和5.html,如果存在正常显示,不存在就去跳转到@qwe
     try_files /4.html /5.html @mq;   
}

 location @mq {
    rewrite ^/(.*)$   http://www.baidu.com;       # 跳转到百度页面
 }
}

2.2 跳转指定文件

server {
   listen 8000;
   server_name 127.0.0.1;
   
   
   location / {
       root html;
       index index.html;
       # 去根目录查找4.html 5.html 6.html 返回第一个找到的文件
       try_files /4.html /5.html /6.html;
  }

2.3 将请求跳转到后端

upstream mydjango{
        server 127.0.0.1:8001;
}


server {
        listen 80;
        server_name www.0528.ltd;

        location / {

        root /opt/dist;
        index index.html;
        # 尝试解析文件/文件夹,解析不到,跳到后端处理
        try_files $uri $uri/ @mq;

        }

        location @mq {
                # 负载均衡的配置
                proxy_pass http://mydjango;
        }
}

3. 错误

  • try_files 按顺序检查文件是否存在,返回第一个找到的文件,至少需要两个参数,但最后一个是内部重定向也就是说和rewrite效果一致。
  • 可以用一个状态码 (404)作为最后一个参数。如果不注意会有死循环造成500错误。
  • 错误代码
location ~.*\.(gif|jpg|jpeg|png)$ {
        root /web/wwwroot;
        try_files /static/$uri $uri;
}


原意图是访问http://example.com/test.jpg时,
先去检查/web/wwwroot/static/test.jpg是否存在,
不存在就取/web/wwwroot/test.jpg。

但由于最后一个参数是一个内部重定向,
所以并不会检查/web/wwwroot/test.jpg是否存在,
只要第一个路径不存在,就会重定向,
然后再进入这个location造成死循环。
结果出现500 Internal Server Error
  • 修改之后的代码
location ~.*\.(gif|jpg|jpeg|png)$ {
        root /web/wwwroot;
        try_files /static/$uri $uri 404;
}


这样才会先检查/web/wwwroot/static/test.jpg是否存在,
不存在就/web/wwwroot/test.jpg
再不存在则返回404 not found

  • 27
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骑猪去兜风z1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值