插件窝 干货文章 Nginx配置React项目时报404怎么解决

Nginx配置React项目时报404怎么解决

Nginx 配置 React proxy 819    来源:    2025-04-24

解决Nginx配置React项目报404错误

当你在Nginx中配置React项目遇到404错误时,通常是由于路由或静态文件服务配置不当导致的。以下是几种常见原因及解决方案:

1. 基础配置问题

确保你的Nginx配置中已经正确指定了React项目的构建目录:

server {
    listen 80;
    server_name yourdomain.com;

    root /path/to/your/react/build;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

关键点: - root 指向React项目build后的目录 - try_files 确保所有路由都回退到index.html

2. 处理客户端路由

React使用客户端路由(如React Router)时,需要确保Nginx将所有非静态资源请求重定向到index.html:

location / {
    try_files $uri $uri/ /index.html;
}

3. 静态资源404

如果静态资源(JS/CSS文件)报404,检查:

location /static/ {
    alias /path/to/your/react/build/static/;
    expires 1y;
    access_log off;
    add_header Cache-Control "public";
}

4. API代理配置

如果你的React应用需要访问后端API,需要配置代理:

location /api/ {
    proxy_pass http://backend-server:port/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

5. 完整示例配置

server {
    listen 80;
    server_name yourdomain.com;

    root /var/www/react-app/build;
    index index.html;

    # 处理主应用
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 静态资源缓存
    location /static/ {
        alias /var/www/react-app/build/static/;
        expires 1y;
        access_log off;
        add_header Cache-Control "public";
    }

    # API代理
    location /api/ {
        proxy_pass http://localhost:3000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    # 其他配置
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}

6. 检查步骤

  1. 确认React项目已正确构建(npm run build
  2. 确认Nginx配置中的路径正确
  3. 检查Nginx错误日志:/var/log/nginx/error.log
  4. 重载Nginx配置:sudo nginx -t && sudo systemctl reload nginx
  5. 清除浏览器缓存测试

如果问题仍然存在,请提供更详细的错误信息和你的Nginx配置,我可以帮你进一步分析。