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

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

Nginx location proxy header 642    来源:    2025-04-22

解决Nginx配置React项目报404问题

当使用Nginx部署React项目时遇到404错误,通常是由于路由配置或静态文件服务设置不当导致的。以下是几种常见解决方案:

1. 基本配置问题

检查root目录设置

确保Nginx配置中的root指向了React项目的构建目录(通常是builddist):

server {
    listen 80;
    server_name yourdomain.com;

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

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

2. 路由问题(前端路由404)

React使用客户端路由时,需要Nginx将所有请求重定向到index.html:

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

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

4. 静态资源缓存问题

有时浏览器缓存可能导致问题,可以添加缓存控制头:

location /static/ {
    expires 1y;
    add_header Cache-Control "public";
}

location / {
    try_files $uri $uri/ /index.html;
    add_header Cache-Control "no-cache, no-store, must-revalidate";
}

5. 完整示例配置

server {
    listen 80;
    server_name yourdomain.com;

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

    # 处理React路由
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 代理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;
    }

    # 静态资源缓存
    location /static/ {
        expires 1y;
        add_header Cache-Control "public";
    }

    # 禁用favicon.ico日志
    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    # 禁用robots.txt日志
    location = /robots.txt {
        log_not_found off;
        access_log off;
    }
}

6. 其他检查项

  1. 确保React项目已正确构建(运行npm run buildyarn build
  2. 检查Nginx错误日志:/var/log/nginx/error.log
  3. 确认文件权限正确(Nginx用户需要有访问构建目录的权限)
  4. 重启Nginx服务:sudo systemctl restart nginx

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