Nginx之 try_files 指令

location / {
            try_files $uri $uri/ /index.php;
}

當用戶請求 http://localhost/example 時,這裏的 $uri 就是 /example。
try_files 會到硬盤裏嘗試找這個文件。若是存在名爲 /$root/example(其中 $root 是項目代碼安裝目錄)的文件,就直接把這個文件的內容發送給用戶。
顯然,目錄中沒有叫 example 的文件。而後就看 $uri/,增長了一個 /,也就是看有沒有名爲 /$root/example/ 的目錄。
又找不到,就會 fall back 到 try_files 的最後一個選項 /index.php,發起一個內部 「子請求」,也就是至關於 nginx 發起一個 HTTP 請求到 http://localhost/index.php。php

-----------------------------------------------------------------------------------------------------------html

try_files 指令做用於(server 和 location 上下文)用於按序檢測文件是否存在,並返回第一個找到的文件。nginx

server {
    root /www/nginx;
    index index.html index.jsp;

    charset utf-8;
    access_log /var/log/nginx/host.access.log main;
    error_log /var/log/nginx/host.error.log error;

    location ^~ /test/ {
        index index.html;
        try_files /2.html /1.html /test/test2.html @bd;
    }

    location @bd {
        rewrite ^/(.*)$ http://www.google.com;
    }
}

/ 表示 root 所在的目錄,1.html 文件前需添加 /,不然請求的格式爲 /www/nginx1.html。jsp

以 /test/ 開頭的 URL 將會匹配 location ^~ /test/ { ... },而後 try_files 指令會分別查找 /www/nginx/2.html、/www/nginx/1.html、/test/test2.html 以及 @bd。google

若前三個 HTML 文件均不存在,則會匹配(內部重定向) location @bd { ... }。spa

相關文章
相關標籤/搜索