nginx 常用命令之 try_files

大家好,我是 17。今天和大家聊聊 try_files。

try_files

try_files file ... uri;
try_files file ... =code;

举两个例子,对应这两种语法。

location /images/ {
    try_files $uri /images/default.gif;
}

location = /images/default.gif {
    expires 30d;
}
location / {
    try_files $uri $uri/index.html $uri.html =404;
}

=404 的 等号 是必须的

try_file 后面必须有一个file, 一个 url 或 code,file 可以有多个。

简单来说,try_file 按顺序检查 file,如果是文件夹,请在 file后加 / ,如果 file 都不存在,根据最后一个参数做跳转。

借这个机会说一下 @ 在location 中的用法。 @ 相当于命名了一个变量。

location / {
    try_files /system/maintenance.html
              $uri $uri/index.html $uri.html
              @mongrel;
}
location @mongrel {
    proxy_pass http://mongrel;
}

try_files 的一个应用场景就是单面应用.

location / {
 try_files $uri $uri/ /index.html
 
}

如果请求的是 /a, 首先会查找 a 文件 是否存在,然后找 a 目录是否存在,如果都不存在,转到 /index.html。 再次命中 location / ,再次执行 try_files,这回找到index.html 返回。

注意:如果 index.html 不存在,会报 500,所以用 try_files的时候,要避免多次命中,最后的跳转最好转到别处。

location / {
 try_files $uri $uri/ /index.html 
}
location /index.html{
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IAM17前端

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

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

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

打赏作者

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

抵扣说明:

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

余额充值