zoukankan      html  css  js  c++  java
  • nginx中的try_files指令解释

    try_files 指令的官方介绍比较让人摸不着头脑,经网上一番总结查看,try_files最核心的功能是可以替代rewrite。

     
    try_files
     
    语法: try_files file ... uri    或  try_files  file ... = code
     
    默认值: 无
     
    作用域: server location
     
    Checks for the existence of files in order, and returns the first file that is found. A trailing slash indicates a directory - $uri /. In the event that no file is found, an internal redirect to the last parameter is invoked. Do note that only the last parameter causes an internal redirect, former ones just sets the internal URI pointer. The last parameter is the fallback URI and *must* exist, or else an internal error will be raised. Named locations can be used. Unlike with rewrite, $args are not automatically preserved if the fallback is not a named location. If you need args preserved, you must do so explicitly:
     
    try_files $uri $uri/ /index.php?q=$uri&$args;
    按顺序检查文件是否存在,返回第一个找到的文件。结尾的斜线表示为文件夹 -$uri/。如果所有的文件都找不到,会进行一个内部重定向到最后一个参数。
     
    务必确认只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向。 最后一个参数是回退URI且必须存在,否则将会出现内部500错误。
     
    命名的location也可以使用在最后一个参数中。与rewrite指令不同,如果回退URI不是命名的location那么$args不会自动保留,如果你想保留$args,必须明确声明。
     
    try_files $uri $uri/ /index.php?q=$uri&$args;
     
     
     
    实例分析
     
    try_files 将尝试你列出的文件并设置内部文件指向。
     
    例如:
     
    try_files /app/cache/ $uri @fallback; 和  index index.php index.html;
     它将检测$document_root/app/cache/index.php,$document_root/app/cache/index.html 和 $document_root$uri是否存在,如果不存在着内部重定向到 @fallback 。
     
    你也可以使用一个文件或者状态码 (=404)作为最后一个参数,如果是最后一个参数是文件,那么这个文件必须存在。
     
    需要明确的是出最后一个参数外 try_files 本身不会因为任何原因产生内部重定向。
     
     
     
     
     
    例如nginx不解析PHP文件,以文本代码返回
     
    try_files $uri /cache.php @fallback;
    因为这个指令设置内部文件指向到 $document_root/cache.php 并返回,但没有发生内部重定向,因而没有进行location段处理而返回文本 。
     
    (如果加上index指令可以解析PHP是因为index会触发一个内部重定向)
    转载:
    http://www.2cto.com/os/201210/164157.html
    .htaccess
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [QSA,L]
    在 Nginx 下, 添加以下声明:
    
        location / {
           try_files $uri $uri/ /index.php;
        }
    
    https://git.oschina.net/os621/ROCBOSS
  • 相关阅读:
    面试题 41 和为s的两个数字VS 和为S的连续整数序列
    面试题 40 数组中只出现一次的数字
    面试题 39 二叉树的深度
    面试题 38数字在排序数组中出现的次数
    面试题 37 两个链表的第一个公共节点
    面试题36 数组中的逆序对
    面试题 35 第一个出现的字符
    省选模拟65 题解
    省选模拟64 题解
    省选模拟63 题解
  • 原文地址:https://www.cnblogs.com/wawahaha/p/4641691.html
Copyright © 2011-2022 走看看