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

Laravel项目Ajax/Livewire在XAMPP Apache失效,仅php artisan serve可正常运行

问题分析与解决方案

核心原因

Laravel的路由依赖Apache的mod_rewrite模块实现URL重写,XAMPP默认可能未开启该模块,或者项目根目录的.htaccess规则未被Apache识别,导致Ajax/Livewire请求的路由无法被正确解析,从而返回404错误。而php artisan serve使用PHP内置服务器,默认支持Laravel的路由规则,因此功能正常。

解决方案

1. 开启Apache的mod_rewrite模块

  • 打开XAMPP控制面板,点击Apache的Config按钮,选择httpd.conf文件
  • 找到#LoadModule rewrite_module modules/mod_rewrite.so行,去掉开头的#注释
  • 保存文件,重启Apache服务

2. 确保.htaccess文件生效

  • 检查Laravel项目public目录下是否存在.htaccess文件,默认内容如下:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
  • 若文件不存在,手动创建并添加上述内容
  • 打开httpd.conf,找到对应DocumentRoot的<Directory>配置段(通常是C:/xampp/htdocs),将AllowOverride None改为AllowOverride All,确保Apache允许读取.htaccess规则
  • 保存后重启Apache

3. 配置虚拟主机(推荐)

直接放在htdocs下易引发路由解析问题,建议配置虚拟主机:

  • 打开XAMPP的apache/conf/extra/httpd-vhosts.conf文件
  • 添加如下配置(替换为你的项目路径和自定义域名):
<VirtualHost *:80>
    DocumentRoot "C:/xampp/htdocs/your-laravel-project/public"
    ServerName your-project.test
</VirtualHost>
  • 打开系统hosts文件(Windows:C:\Windows\System32\drivers\etc\hosts;Linux/macOS:/etc/hosts),添加一行:127.0.0.1 your-project.test
  • 重启Apache,通过your-project.test访问项目

4. Livewire额外检查

若为Livewire组件问题,还需确认:

  • 在.env文件中设置正确的APP_URL:APP_URL=http://your-project.test(对应虚拟主机域名)
  • 运行php artisan livewire:publish --config发布配置,确保config/livewire.php中的asset_url配置正确

5. 清除缓存

完成配置后,运行以下命令清除Laravel缓存:

php artisan cache:clear
php artisan route:clear
php artisan config:clear

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:42:14