在Nginx配置文件中(通常是nginx.conf
或站点配置文件),可以通过以下方式配置404页面:
server {
# ...其他配置...
error_page 404 /404.html;
location = /404.html {
root /path/to/your/error/pages;
internal;
}
}
server {
# ...其他配置...
error_page 404 /custom_404.html;
location = /custom_404.html {
root /usr/share/nginx/html/errors;
internal;
}
}
对于AJAX请求,我们通常希望返回JSON格式的错误信息而非HTML页面:
server {
# ...其他配置...
error_page 404 @ajax404;
location @ajax404 {
if ($http_x_requested_with = XMLHttpRequest) {
default_type application/json;
return 404 '{"error": "Resource not found", "code": 404}';
}
# 非AJAX请求返回普通404页面
return 404 /404.html;
}
location = /404.html {
root /path/to/your/error/pages;
internal;
}
}
另一种方法是检查Content-Type头:
location @ajax404 {
if ($http_accept ~* "application/json") {
default_type application/json;
return 404 '{"error": "Not found", "status": 404}';
}
return 404 /404.html;
}
map $http_accept $error_response_type {
default "html";
~*application/json "json";
}
server {
# ...其他配置...
error_page 404 @error404;
location @error404 {
if ($error_response_type = "json") {
default_type application/json;
return 404 '{"error": "Not found", "status": 404}';
}
return 404 /404.html;
}
}
如果需要从后端生成错误页面:
error_page 404 /error-handler.php;
location = /error-handler.php {
internal;
fastcgi_pass php-fpm;
include fastcgi_params;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param ERROR_CODE 404;
}
前端JavaScript处理404响应的示例:
fetch('/api/resource')
.then(response => {
if (!response.ok) {
if (response.status === 404) {
return response.json().then(err => {
// 处理JSON格式的错误响应
console.error('API Error:', err);
throw err;
});
}
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// 处理正常数据
})
.catch(error => {
// 处理错误
});
通过以上配置,你可以实现Nginx对普通请求返回自定义404页面,同时对AJAX请求返回JSON格式的错误信息。