從 Http 伺服器提供 Web 應用程式錯誤訊息

從 Http 伺服器提供 Web 應用程式錯誤訊息

我有 nginx 作為 http 伺服器,以 tomcat 作為後端(使用 proxy_pass)。它工作得很好,但我想定義自己的錯誤頁面(404、500 等),並且它們由 nginx 而不是 tomcat 提供服務。例如我有以下資源:

https://domain.com/resource

這是不存在的。如果我 [GET] 該 URL,那麼我會從 Tomcat 而不是從 nginx 收到 Not Found 訊息。

我想要的是,每次 Tomcat 以 404(或任何其他錯誤訊息)回應時,nginx 都會向用戶發送一條訊息:一些可由 nginx 存取的 html 檔案。

我配置 nginx 伺服器的方式非常簡單,只需:

location / {
    proxy_pass   http://localhost:8080/<webapp-name>/;
}

我已經配置了連接埠 8080,即 tomcat,無法從本機外部存取。

我認為location在 nginx 配置中使用不同的指令不會起作用,因為有一些資源依賴 URL:

https://domain.com/customer/<non-existent-customer-name>/[GET]

將始終返回 404(或任何其他錯誤訊息),同時:

https://domain.com/customer/<existent-customer>/[GET]

將返回與 404 不同的任何內容(客戶存在)。

有沒有辦法使用 Nginx(http 伺服器)來提供 Tomcat(應用程式伺服器)錯誤訊息?檢查proxy_pass指令發送的訊息並據此採取行動?

答案1

好的,我找到了。在server我正在使用的 nginx 網站設定部分:

error_page 404 /404.html;
location = /404.html {
    root /var/www/nginx;
}

location / {
    proxy_pass http://localhost:8080/api/;
    proxy_intercept_errors on;
}

您需要proxy_intercept_errors on為 nginx新增攔截他們。 Nginx 只會攔截您用error_page.

相關內容