命名位置作為 try_files 指令中的後備

命名位置作為 try_files 指令中的後備

我在理解 Nginx 中的路由處理時遇到了問題。

server {
    listen 80;
    listen [::]:80;
    server_name my_domain;

    root /var/www/ep;

    index index.html;

    error_page 403 404 /my403.html;

    location /images/ {
            try_files $uri @not_found;
    }

    location @not_found {
            root /var/www/ep/not_found;
            try_files NON_EXISTENT_1 /not_found.jpg;
    }
}

對於上面的配置,當我訪問http://my_domain/images/xyz.png或者http://my_domain/images/我希望@not_found位置指令發生,從/var/www/ep/not_found/not_found.jpg(它存在)返回圖像,但不知何故/var/www/ep/not_found.jpg正在嘗試路徑(它不存在)。它導致顯示/my403.html文件。

我想使用命名位置方法(@not_found)。

有人能解釋一下這裡發生了什麼事嗎?

為什麼/var/www/ep/not_found/not_found.jpg不送達?

答案1

您將其放在語句/not_found.jpg的末尾try_files,這使其成為 URI 術語,這意味著nginx將搜尋新的location來處理請求。你應該做到不是最後,例如:

try_files /not_found.jpg =404;

這個文件了解更多。


作為命名的替代方案location,您可以使用:

location /images/ {
        try_files $uri /not_found.jpg;
}
location = /not_found.jpg {
    root /var/www/ep/not_found;
}

這個文件了解詳情。

相關內容