為什麼 nginx.conf 中的 return 語句可能會向瀏覽器傳回純文字檔案位置,而不是要呈現的實際檔案?

為什麼 nginx.conf 中的 return 語句可能會向瀏覽器傳回純文字檔案位置,而不是要呈現的實際檔案?

環境:Nginx、Node.js

我正在 Nginx 中嘗試錯誤處理,但沒有成功返回文件。

在下面的簡化中,ngxinx.conf如果 httprequest_method不是GETHEAD或者POST我希望伺服器回傳 405.html 錯誤頁面。

希望輸出:405.html 被傳送到瀏覽器。

實際輸出:該純文字被傳送到瀏覽器。 http://www.example.com/html/405.html

注意:我正在 Postman 中對此進行測試,因此我不必在 Chrome 中安裝允許向伺服器發送各種 HTTP 方法的附加擴充功能。

我的配置的相關部分:

server {

    include conf.d/listen-80;

    server_name example.com www.example.com;

    if ($request_method !~ ^(GET|HEAD|POST)$) {
        return 405 $scheme://www.example.com/html/405.html;
    }

    return 301 https://www.example.com$request_uri;

}

server {

    include conf.d/listen-443;

    server_name example.com;

    include conf.d/letsencrypt;

    if ($request_method !~ ^(GET|HEAD|POST)$) {
        return 405 $scheme://www.example.com/html/405.html;
    }

    return 301 https://www.example.com$request_uri;

}

server {

    include conf.d/listen-443;

    server_name www.example.com;

    include conf.d/letsencrypt;

    if ($request_method !~ ^(GET|HEAD|POST)$) {
        return 405 $scheme://www.example.com/html/405.html;
    }

    root /srv/example/views/public;

    location ~* \.(htm|html)$ {
        include conf.d/content-security-policy-html-rendered;
        include conf.d/cache-control-30-days;
        include conf.d/security-headers-html-rendered;
    }
}

答案1

後面的 URLreturn nnn僅被視為重定向程式碼(301、302、303、307 和 308 狀態碼)的目標 URL。該文件沒有清楚地說明當程式碼是其他東西時它會做什麼。

若要在您的情況下取得錯誤頁面,請使用以下命令:

if ($request_method !~ ^(GET|HEAD|POST)$) {
    return 405;
}

error_page 405 /html/405.html;

/html/405.html這將告訴 nginx在返回狀態代碼 405 時發送。

相關內容