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

Laravel+React部署后提交帖子跳转个人页404及图片无法访问问题

问题解决:React前端+Laravel后端部署后跳转与图片访问404

问题描述

  • React前端托管在主域名https://example.com,Laravel管理面板及API部署在子域名https://admin.example.com
  • 本地开发环境一切正常,线上部署后出现两个问题:
    1. 用户提交帖子后,跳转至https://example.com/user/my-account时返回404错误
    2. 上传图片存储在public_html/admin/public/images目录,但通过https://admin.abc.com/images/xxx.jpg访问时返回404,前端无法显示

解决方案

一、前端路由跳转404修复

1. 修正路由守卫逻辑

你的ProtectedAuthRoute逻辑完全颠倒:已认证用户反而被跳转到主页,导致合法用户无法访问个人页。修改为:

const ProtectedRoute = ({ element }) => {
    const { isAuthenticated } = useSelector((state) => state.auth);
    // 已认证则展示页面,未认证跳转到登录页
    return isAuthenticated ? element : <Navigate to="/login" />;
};

2. 配置前端服务器重写规则

React是单页应用,直接访问路由或刷新页面时,服务器会找不到对应文件,需配置重定向到index.html:

  • Nginx配置:
    location / {
        try_files $uri $uri/ /index.html;
    }
    
  • Apache配置(.htaccess):
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
    

3. 移除不必要的页面刷新

跳转后无需强制刷新,删除window.location.reload(),保留React路由的单页跳转体验:

// 删除此行代码
// window.location.reload();

二、图片访问404修复

1. 确认目录权限与存在性

检查public_html/admin/public/images目录是否存在,且服务器进程拥有读写权限:

# 设置正确的所有者与权限
chown -R www-data:www-data public_html/admin/public/images
chmod -R 755 public_html/admin/public/images

2. 修正图片URL生成逻辑

$request->root()可能因部署环境配置错误生成错误域名(如示例中的admin.abc.com),建议通过Laravel配置确保URL正确:

  • 先在.env中设置正确的子域名:
    APP_URL=https://admin.example.com
    
  • 然后修改图片URL生成代码:
    // 替换原有的图片URL赋值行
    $post->image = url('/images/' . $fileName);
    

3. 确认Laravel站点根目录映射

确保服务器将Laravel的站点根目录指向public_html/admin/public,而非public_html/admin,否则/images路径无法被正确解析。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 20:26:13