在本地localhost运行Laravel仅显示文件,该如何修复?
Laravel本地运行显示文件列表的修复方法
出现这种情况大多是因为服务器没有正确指向Laravel的入口文件(public/index.php),或者相关配置没到位,下面是几种常见的解决办法:
1. 直接调整访问路径
Laravel的前端入口在项目的public目录下,如果你现在访问的是项目根目录(比如localhost/laravel-project),改成访问localhost/laravel-project/public即可正常加载页面。
2. 配置虚拟主机(推荐)
如果不想每次都输入public,可以给项目配置虚拟主机,直接用自定义域名访问:
Apache(XAMPP/WAMP)
- 打开Apache的
httpd-vhosts.conf文件(XAMPP路径一般是C:\xampp\apache\conf\extra\httpd-vhosts.conf),添加以下配置:
<VirtualHost *:80> DocumentRoot "C:/xampp/htdocs/你的项目路径/public" ServerName laravel.test </VirtualHost>
- 修改系统hosts文件(Windows路径:
C:\Windows\System32\drivers\etc\hosts;Linux/macOS:/etc/hosts),添加一行:
127.0.0.1 laravel.test
- 重启Apache服务,之后直接访问
laravel.test就能进入Laravel页面。
Nginx
打开Nginx的配置文件,添加或修改server块:
server { listen 80; server_name laravel.test; root /你的项目绝对路径/public; index index.php; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # 根据你的PHP版本调整路径 fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; } }
重启Nginx后,访问laravel.test即可。
3. 启用Apache的rewrite模块
如果调整路径后还是不行,可能是mod_rewrite没启用:
- 打开Apache的
httpd.conf文件,找到#LoadModule rewrite_module modules/mod_rewrite.so,去掉前面的#注释。 - 确保项目
public目录下的.htaccess文件存在,要是没有,从Laravel官方仓库复制一份标准的.htaccess内容过来。 - 重启Apache服务。
4. 修复目录权限问题
Linux/macOS环境下,确保Laravel的storage和bootstrap/cache目录有写入权限,运行以下命令:
chmod -R 775 storage bootstrap/cache chown -R www-data:www-data storage bootstrap/cache # 服务器用户组根据实际情况调整,比如nginx
内容的提问来源于stack exchange,提问作者atozcodes
相关产品推荐
相关产品推荐

