当使用Nginx部署React项目时遇到404错误,通常是由于路由配置或静态文件服务设置不当导致的。以下是几种常见解决方案:
确保Nginx配置中的root指向了React项目的构建目录(通常是build
或dist
):
server {
listen 80;
server_name yourdomain.com;
root /path/to/your/react-project/build;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
React使用客户端路由时,需要Nginx将所有请求重定向到index.html:
location / {
try_files $uri $uri/ /index.html;
}
如果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;
}
有时浏览器缓存可能导致问题,可以添加缓存控制头:
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";
}
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;
}
}
npm run build
或yarn build
)/var/log/nginx/error.log
sudo systemctl restart nginx
如果问题仍然存在,请提供更详细的错误信息和Nginx配置,我可以帮助进一步诊断。