如何在 Nginx 中為特定路徑內的所有 404 傳回預設檔?

如何在 Nginx 中為特定路徑內的所有 404 傳回預設檔?

我有一個本地化資料夾,其中包含一堆語言(如 JSON)文件,並且我的 web 應用程式嘗試讀取瀏覽器的語言以獲取相應的 JSON 文件。

在某些場景下,對應的語言檔案不存在,nginx理應回傳404。但是,我想返回到預設語言檔案的臨時重定向。

我已經嘗試過這個,但似乎不起作用。我究竟做錯了什麼?

    location /static/l10n {
            try_files $uri @missing_language;
    }

    location @missing_language {
            rewrite ^ /static/l10n/en-us.json break;
    }

編輯2:所以我嘗試try_files像這樣調整一下。

    location /static/l10n {
            try_files $uri /static/l10n/en-us.json;
    }

但現在我收到 500 錯誤。日誌說*35 rewrite or internal redirection cycle while internally redirecting

編輯3:我完整的 nginx 設定在這裡 -https://gist.github.com/paambaati/9782e95b2e9af899b154

答案1

使用error_page

要使用給定文件作為 404 回應 - 使用錯誤頁面

location /static/l10n {
    error_page 404 = /static/l10n/en-us.json;
}

請注意使用=來充當/static/l10n/en-us.jsonhttp 200。

相關內容