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

共享主机public_html下部署Laravel CMS至指定文件夹的方法

部署Laravel CMS到共享主机子目录的解决方案

1. 调整文件部署结构

  • 在public_html下创建cms目录,将Laravel项目的全部文件(包括app、bootstrap、config、vendor、.env、artisan等,以及自带的public文件夹)上传到public_html/cms
  • 将Laravel自带public目录中的所有内容(index.php、.htaccess、favicon.ico等)移动到public_html/cms目录下(覆盖同名文件),随后删除空的public文件夹
  • 修改public_html/cms/index.php中的路径指向,确保能加载核心文件:
// 替换原路径为当前目录的核心文件
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';

2. 配置.env文件

修改public_html/cms/.env中的关键参数:

  • APP_URL=https://你的域名/cms
  • APP_ENV=production
  • APP_DEBUG=false(生产环境必须关闭)

3. 设置服务器重写规则

Apache环境

在public_html/cms目录下创建或修改.htaccess,添加Laravel重写规则:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # 处理授权头
    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>

确保根目录.htaccess不会干扰子目录规则,避免路由冲突。

Nginx环境

联系主机提供商修改站点配置,添加如下规则:

location /cms {
    try_files $uri $uri/ /cms/index.php?$query_string;
}

部分主机支持在根目录创建nginx.conf自定义规则,可自行尝试。

4. 配置路由前缀(可选)

如果希望所有CMS路由自动带上/cms前缀,可在app/Providers/RouteServiceProvider.php中设置全局前缀:

public function boot()
{
    $this->routes(function () {
        Route::prefix('cms')
            ->middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/web.php'));
    });
}

也可以在routes/web.php中用路由组包裹单个路由:

Route::prefix('cms')->group(function () {
    Route::get('/', function () {
        return view('welcome');
    });
    // 其他CMS路由...
});

5. 权限设置

确保目录权限符合主机要求:

  • storage和bootstrap/cache目录设置为可写权限(通常为755或775,禁止使用777权限)

6. 清除缓存

如果主机支持SSH,进入public_html/cms目录执行以下命令:

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

无SSH权限时,手动删除storage/framework/cache、storage/framework/sessions、storage/framework/views及bootstrap/cache下的所有文件。

内容的提问来源于stack exchange,提问作者Krati Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:25:23