Laravel+Vue SPA部署Apache后所有路由返回404错误排查
问题核心原因
一共3个直接导致故障的点:
- Apache虚拟主机配置的域名和实际访问域名不匹配:配置里写的
ServerName example.com、ServerAlias www.example.com,实际业务用的是my.example.com,请求无法正确匹配到该虚拟主机的规则。 - 前后端均缺失必要的URL重写规则:
- Vue编译的dist目录作为前端根目录,没有配置history路由模式的回退规则,所有非根路径的前端请求都会直接报404,且dist目录本身没有配置目录权限规则。
- Laravel后端用Alias做路径映射时,没有配置重写规则去除
/api前缀,请求到达Laravel时携带的路径仍以/api开头,和Laravel路由文件里定义的路由规则不匹配,直接抛出NotFoundHttpException,和你抓到的报错完全对应。
- Laravel配置存在生产环境不规范项:
.env里开启了debug、应用环境设为local,Sanctum配置里硬编码域名容易和env配置冲突,且改配置后大概率没清配置缓存。
可直接落地的修复方案
- 替换原Apache虚拟主机配置为以下内容:
<VirtualHost *:80> ServerName my.example.com ServerAlias www.my.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/my.example.com/dist # 前端Vue SPA配置 <Directory /var/www/my.example.com/dist> Options FollowSymLinks AllowOverride All Require all granted RewriteEngine On RewriteBase / # history路由回退:所有非静态文件请求全部走index.html RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </Directory> # Laravel后端接口配置 Alias "/api" "/var/www/my.example.com/api/public" Alias "/sanctum" "/var/www/my.example.com/api/public" <Directory /var/www/my.example.com/api/public> Options Indexes FollowSymLinks AllowOverride All Require all granted RewriteEngine On RewriteBase /api # 转发请求到Laravel入口,处理路由解析 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /api/index.php [L] </Directory> ErrorLog ${APACHE_LOG_DIR}/my-example-error.log CustomLog ${APACHE_LOG_DIR}/my-example-access.log combined </VirtualHost>
- 执行以下命令开启Apache重写模块、重启服务生效:
a2enmod rewrite systemctl restart apache2
- 调整Laravel配置并清理缓存:
- 修改
.env文件,将APP_ENV改为production,APP_DEBUG改为false,避免生产环境泄露敏感信息 - 去掉
config/sanctum.php里硬编码的域名字符串,统一从.env读取配置,避免多配置源冲突 - 进入Laravel项目目录执行清理命令:
- 修改
php artisan config:clear php artisan route:clear php artisan cache:clear
- 配置Laravel目录权限,保证Web服务用户有写入权限:
chown -R www-data:www-data /var/www/my.example.com/api chmod -R 755 /var/www/my.example.com/api/storage chmod -R 755 /var/www/my.example.com/api/bootstrap/cache
验证方法
配置生效后先直接访问已定义的后端接口路径(比如/api/login),确认接口返回正常,再访问前端页面,测试路由跳转、子路径刷新操作,确认不再出现404错误。



内容的提问来源于stack exchange,提问作者Lol Master
相关产品推荐
相关产品推荐

