Laravel 10子目录部署:去除URL中public路径并解决404错误
Laravel 10 子目录部署解决方案
1. 修正根目录的 .htaccess 配置
将 /laravel-project/ 下的 .htaccess 替换为以下内容,确保请求正确转发到 public/index.php:
<IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^$ public/index.php [L] RewriteRule ^((?!public/).*)$ public/$1 [L] </IfModule>
该规则会将根路径请求直接指向 public/index.php,同时把所有非public/开头的请求转发到对应目录下的文件或路由。
2. 调整 public 目录的 .htaccess
修改 /laravel-project/public/ 下的 .htaccess,添加 RewriteBase 适配子目录:
<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # 指定子目录路径 RewriteBase /laravel-project/ # 处理授权头 RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # 移除末尾斜杠(非目录请求) RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # 将所有非文件/目录请求转发到前端控制器 RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule>
3. 环境变量配置与缓存清理
- 保留
.env中正确的APP_URL设置,移除非官方支持的APP_DIR:APP_URL=http://example.com/laravel-project - 执行命令清除配置与路由缓存,确保新设置生效:
php artisan config:clear php artisan route:clear
4. 虚拟主机补充说明
如果虚拟主机允许自定义配置,优先将站点的DocumentRoot指向 /laravel-project/public;若必须保持根目录为 /laravel-project,上述 .htaccess 配置即可满足需求。
内容的提问来源于stack exchange,提问作者Rafaucau
相关产品推荐
相关产品推荐

