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一起使用將沒有效果)