You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用如何为不存在的页面返回404状态码?

React单页应用实现404状态码返回方案

别信那种“React只能返回200”的说法——前端本身确实只返回页面内容,但服务器层面的配置才是解决404状态码的核心。单页应用的前端路由在浏览器端解析,服务器默认会把所有请求都返回index.html(状态码200),所以得从服务器或构建方式入手调整:

一、服务器端配置(主流场景)

1. Nginx配置

找到你的Nginx站点配置文件,添加如下规则,确保不存在的路由返回404状态码:

server {
  listen 80;
  server_name your-domain.com;
  root /path/to/react/build; # React打包后的build目录路径
  index index.html;

  # 静态资源缓存配置
  location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
  }

  # 处理前端路由,不存在的路径返回404页面并设置状态码
  location / {
    try_files $uri $uri/ @404;
  }

  location @404 {
    return 404 /404.html;
  }

  location = /404.html {
    root /path/to/react/build;
    add_header Status "404 Not Found";
  }
}

2. Apache配置

在React项目的build目录下创建.htaccess文件,写入:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
# 如果请求的不是文件或目录,返回404页面并设置状态码
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.html [R=404,L]

3. Netlify/Vercel等静态托管平台

  • Netlify:在项目根目录创建_redirects文件,内容:
/* /404.html 404
  • Vercel:在vercel.json中配置:
{
  "routes": [
    { "handle": "filesystem" },
    { "src": "/.*", "dest": "/404.html", "status": 404 }
  ]
}

二、用静态站点生成/服务端渲染框架

如果项目还在初期,直接用Next.js、Gatsby这类框架更省心——它们天生支持路由的服务端处理,只需创建404.js(Next.js)或src/pages/404.js(Gatsby),访问不存在的路由时,服务器会自动返回404状态码。

三、前端路由配合(仅用户界面)

在React路由里添加一个兜底路由,给用户显示404页面,但注意这只是视觉效果,真正的状态码还是要靠服务器配置:

import { Routes, Route } from 'react-router-dom';

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
      {/* 匹配所有未定义的路由 */}
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

function NotFound() {
  return <h1>404 - 页面不存在</h1>;
}

内容的提问来源于stack exchange,提问作者Aleksei Vlasov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:04:53