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

Laravel 8子目录部署.htaccess配置问题:API访问404错误

Laravel 8子目录部署API出现404问题排查与解决

问题场景

  • 部署结构:webserver根目录下包含mobile-api(Laravel核心文件)和public_html(现有主站文件);public_html内的mobile文件夹作为Laravel的公开目录,存放index.php和.htaccess
  • 已启用.htaccess重写规则,但访问API时返回404,当前使用的.htaccess代码如下:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # 处理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>

更新信息

  • 更新1(7月16日 9:44 GMT+8):mobile作为Laravel公开目录,位于主站public_html的子目录中
  • 更新2(7月17日 00:00 GMT+8):public_html下mobile文件夹的目录结构及文件内容:
    底部为mobile(Laravel公开目录)的文件

解决步骤

1. 修正.htaccess重写规则

由于Laravel公开目录位于子目录/mobile,默认规则未适配子目录路径,需添加RewriteBase并调整规则:

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

    RewriteEngine On
    # 设置重写基准为当前子目录
    RewriteBase /mobile/

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

2. 调整index.php的核心文件路径

打开public_html/mobile/index.php,修正指向Laravel核心文件的相对路径:

// 替换原路径为指向webserver根目录下的mobile-api文件夹
require __DIR__.'/../../mobile-api/vendor/autoload.php';
$app = require_once __DIR__.'/../../mobile-api/bootstrap/app.php';

3. 配置Laravel的环境变量

编辑mobile-api/.env文件,设置正确的API访问地址:

APP_URL=https://你的域名/mobile

4. 验证服务器配置

  • 确认服务器已启用mod_rewrite模块
  • 检查public_html/mobile文件夹及内部文件的权限,确保服务器有可读权限

内容的提问来源于stack exchange,提问作者Muhammad Faiz Abdullah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:41:18