插件窝 干货文章 Nginx中404页面怎么配置及AJAX请求返回404页面

Nginx中404页面怎么配置及AJAX请求返回404页面

404 error 页面 配置 983    来源:    2025-04-21

Nginx 404页面配置及AJAX请求处理方案

一、Nginx 404页面基本配置

1. 基本配置方法

在Nginx配置文件中(通常是nginx.conf或站点配置文件),可以通过以下方式配置404页面:

server {
    # ...其他配置...

    error_page 404 /404.html;
    location = /404.html {
        root /path/to/your/error/pages;
        internal;
    }
}

2. 自定义404页面位置

server {
    # ...其他配置...

    error_page 404 /custom_404.html;
    location = /custom_404.html {
        root /usr/share/nginx/html/errors;
        internal;
    }
}

二、AJAX请求返回404处理

1. 区分AJAX请求和普通请求

对于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;
    }
}

2. 使用Content-Type判断

另一种方法是检查Content-Type头:

location @ajax404 {
    if ($http_accept ~* "application/json") {
        default_type application/json;
        return 404 '{"error": "Not found", "status": 404}';
    }

    return 404 /404.html;
}

三、高级配置方案

1. 统一错误处理

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;
    }
}

2. 动态错误页面

如果需要从后端生成错误页面:

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;
}

四、前端AJAX处理示例

前端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 => {
        // 处理错误
    });

五、注意事项

  1. 确保404页面文件存在且有正确的权限
  2. 测试时清除浏览器缓存,因为浏览器可能会缓存404页面
  3. 对于AJAX请求,确保服务器返回正确的Content-Type头
  4. 在生产环境中,考虑记录404错误以便分析死链

通过以上配置,你可以实现Nginx对普通请求返回自定义404页面,同时对AJAX请求返回JSON格式的错误信息。