JkLSweetMint
JkLSweetMint

Reputation: 1

How do I return a response from the destination server in case of an error in Nginx?

I need to always return in case of errors. 400, 401, 403, 404, 500... my html pages with errors if the response is from the destination server is text/html, otherwise I can return the server's response, I was able to make a configuration that returns my pages globally if html is returned from the destination server, but I can't return the original response in any way. How can something like this be done?

Nginx conf block:

error_page 404 = @handle_error_404; 

default_type text/html;
proxy_intercept_errors on;

location @handle_error_404 {
    internal;

    if ($upstream_http_content_type = "text/html") {
        rewrite /(.*) /internal/errors/404.html;
    }

    if ($upstream_http_content_type != "text/html") {
    }
}

location /internal/errors/ { 
    alias /data/nginx/custom/pages/errors/;
}

Roughly speaking, I need error_page to work only on responses with the text/html content type.

I tried using Lua again, but I also ran into an error that I couldn't fix.

body_filter_by_lua_block {
    local function has_value (tab, val)
        for index, value in ipairs(tab) do
            if value == val then
                return true
            end
        end
 
        return false
    end
 
    local function error_filter ()
        local enableStatuses = {404}
 
        if has_value(enableStatuses, ngx.status) then
            if ngx.header.content_type ~= "text/html" then
                return
            end
 
            local page = "/internal/errors/" .. ngx.status .. ".html"
 
            return ngx.redirect(page)
        end
    end
 
    return error_filter()
}

Error:

openresty: failed to run body_filter_by_lua*: API disabled in the context of body_filter_by_lua*

Upvotes: 0

Views: 24

Answers (0)

Related Questions