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
:
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
location @error_pages {
default_type application/json;
return $status '{"error": "$status", "message": "$error_message"}';
}
注意事项
-
性能优化
-
纯文本响应体积最小,适合高并发场景。
-
-
日志记录
-
确保错误日志开启(
error_log /var/log/nginx/error.log;
)以便排查问题。
-
-
安全
-
避免在错误消息中泄露敏感信息(如服务器路径)。
-
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步