React+Laravel共存VHost配置失效,访问API出现404错误求助
解决React + Laravel同VHost下API 404问题
问题核心
当前配置下,Apache的路由规则优先级冲突或模块干扰,导致API请求未被正确转发到Laravel的public目录,而被React的SPA规则接管,最终触发404错误。
解决方案1:调整VHost配置
修改VirtualHost配置,调整规则顺序并关闭干扰模块,确保API请求优先被处理:
<VirtualHost *:80> ServerName mysite.local # 优先处理API请求,确保Alias规则先生效 Alias /api "${INSTALL_DIR}/www/mysite.local/api/public" <Directory "${INSTALL_DIR}/www/mysite.local/api/public"> Options +Indexes +FollowSymLinks AllowOverride All Require all granted </Directory> # React前端配置,关闭MultiViews避免路径匹配干扰 DocumentRoot "${INSTALL_DIR}/www/mysite.local/frontend/build" <Directory "${INSTALL_DIR}/www/mysite.local/frontend/build"> Options +Indexes +FollowSymLinks -MultiViews AllowOverride All Require all granted # 添加Rewrite规则,排除/api路径,让API请求走Alias RewriteEngine On RewriteCond %{REQUEST_URI} !^/api RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.html [L] </Directory> ErrorLog "${INSTALL_DIR}/logs/mysite.local-error.log" CustomLog "${INSTALL_DIR}/logs/mysite.local-access.log" common </VirtualHost>
解决方案2:修正React的.htaccess(若存在)
如果React build目录下有SPA路由用的.htaccess,需添加排除/api路径的规则,避免接管API请求:
<IfModule mod_rewrite.c> RewriteEngine On # 排除/api开头的请求,让其走Laravel Alias RewriteCond %{REQUEST_URI} !^/api RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.html [L] </IfModule>
解决方案3:验证Laravel配置
- 打开Laravel根目录的
.env文件,确认APP_URL配置正确:APP_URL=http://mysite.local/api - 重新清理并生成路由缓存:
php artisan cache:clear php artisan route:clear php artisan route:cache
测试验证
重启WampServer后,分别测试:
- 前端:
http://mysite.local正常加载React应用 - API:
http://mysite.local/api/hello返回Laravel响应而非404
内容的提问来源于stack exchange,提问作者lttl1234
相关产品推荐
相关产品推荐

