nginx 错误处理

http {
    # 定义错误码到提示信息的映射
    map $status $error_message {
        # 4xx 错误
        ~^4\d{2}$ "Client Error $status: Please check your request.";
        # 5xx 错误
        ~^5\d{2}$ "Server Error $status: Please try again later.";
        # 默认提示
        default "Error $status: An unexpected error occurred.";
    }

    server {
        listen 80;
        server_name example.com;

        # 开启错误拦截
        proxy_intercept_errors on;

        # 统一错误处理入口(覆盖所有 4xx 和 5xx 错误)
        error_page 400-451 500-511 @error_pages;

        # 代理到后端
        location / {
            proxy_pass http://backend;
        }

        # 统一错误处理逻辑
        location @error_pages {
            # 返回纯文本错误信息
            default_type text/plain;
            return $status "$error_message";
        }
    }
}

扩展:

http {
    server {
        listen 80;
        server_name example.com;

        # 开启错误拦截
        proxy_intercept_errors on;

        # 错误页面映射
        error_page 400 /bad_request;
        error_page 403 /forbidden;
        error_page 404 /not_found;
        error_page 500 /server_error;
        error_page 502 /bad_gateway;

        # 纯文本错误处理
        location = /bad_request {
            return 400 "400 Bad Request: The server cannot process your request.";
        }
        location = /forbidden {
            return 403 "403 Forbidden: Access denied.";
        }
        location = /not_found {
            return 404 "404 Not Found: The page does not exist.";
        }
        location = /server_error {
            return 500 "500 Internal Server Error: Please try again later.";
        }
        location = /bad_gateway {
            return 502 "502 Bad Gateway: The upstream server is down.";
        }

        # 正常代理配置
        location / {
            proxy_pass http://backend;
        }
    }
}

扩展选项

1. 如果需要返回 HTML

修改 @error_pages

nginx
复制
location @error_pages {
    default_type text/html;
    return $status "
        <!DOCTYPE html>
        <html>
        <body>
            <h1>Error $status</h1>
            <p>$error_message</p>
        </body>
        </html>
    ";
}

2. 如果需要返回 JSON

nginx
复制
location @error_pages {
    default_type application/json;
    return $status '{"error": "$status", "message": "$error_message"}';
}

注意事项

  1. 性能优化

    • 纯文本响应体积最小,适合高并发场景。

  2. 日志记录

    • 确保错误日志开启(error_log /var/log/nginx/error.log;)以便排查问题。

  3. 安全

    • 避免在错误消息中泄露敏感信息(如服务器路径)。

posted @   锐洋智能  阅读(13)  评论(0)    收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示