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

Vercel部署PHP站点:页面路由与文件引入配置问题求助

解决Vercel部署PHP站点的路由配置问题

核心问题分析

  1. Vercel路由匹配逻辑限制:vercel.json中routes.src仅匹配URL的路径部分,不包含?后的查询参数,所以你写的/page.php?page=(.*)$这类带查询参数的规则完全无效。
  2. PHP文件位置要求:Vercel的PHP运行时仅执行api目录下的PHP文件,原根目录的index.php不在该目录下的话,根本不会被当作PHP函数处理。
  3. 路由优先级问题:路由规则从上到下匹配,具体规则必须放在通用规则前面,否则会被后面的通用规则覆盖。

分步解决方案

1. 调整项目目录结构

将核心PHP文件和页面目录移到api目录下,确保Vercel能识别并执行PHP代码:

项目根目录
├── api/
│   ├── index.php       # 原根目录的index.php移至此处
│   ├── pages/
│   │   ├── about_us.html
│   │   ├── contact_us.html
│   │   └── menu.html
│   └── assets.php      # 处理静态资源的PHP文件(若需保留)
├── css/
├── js/
├── img/
└── vercel.json

2. 修正PHP代码的路径与语法问题

由于index.php现在位于api目录下,需修改文件引入路径避免相对路径错误,同时补上之前缺失的分号:

<html><head><!-- header html here --></head>
<body>
<?php
    $page = $_GET['page'] ?? '';
    if($page == 'about_us'){
        require __DIR__ . "/pages/about_us.html"; // 补充分号,使用绝对路径
    } elseif($page == 'contact_us'){
        require __DIR__ . "/pages/contact_us.html"; // 补充contact_us分支逻辑
    } else {
        require __DIR__ . "/pages/menu.html";
    }
?>
<!-- footer components here -->
</body>
</html>

3. 重新配置vercel.json

根据需求提供两种配置方案:

方案一:支持友好路径(推荐)

访问/about_us直接映射到/api/index.php?page=about_us,配置如下:

{
    "version": 2,
    "functions": {
        "api/index.php": {
            "runtime": "vercel-php@0.6.0"
        },
        "api/assets.php": {
            "runtime": "vercel-php@0.6.0"
        }
    },
    "routes": [
        // 静态资源直接访问,无需经过PHP处理
        { 
            "src": "/(css|js|img)/(.*)$",
            "dest": "/$1/$2"
        },
        // 具体页面路由规则,放在通用规则前
        { 
            "src": "/about_us",
            "dest": "/api/index.php?page=about_us"
        },
        { 
            "src": "/contact_us",
            "dest": "/api/index.php?page=contact_us"
        },
        // 根路径及未匹配路径指向api/index.php
        { 
            "src": "/(.*)",  
            "dest": "/api/index.php" 
        }
    ]
}
方案二:支持原查询参数方式(访问/?page=about_us)

此方式更简单,Vercel会自动传递查询参数到目标PHP文件:

{
    "version": 2,
    "functions": {
        "api/index.php": {
            "runtime": "vercel-php@0.6.0"
        },
        "api/assets.php": {
            "runtime": "vercel-php@0.6.0"
        }
    },
    "routes": [
        { 
            "src": "/(css|js|img)/(.*)$",
            "dest": "/$1/$2"
        },
        { 
            "src": "/(.*)",  
            "dest": "/api/index.php" 
        }
    ]
}

验证部署

提交所有修改到Git仓库,触发Vercel重新部署后测试:

  • 方案一:访问https://你的域名/about_us应显示about_us页面
  • 方案二:访问https://你的域名/?page=about_us应显示about_us页面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:33:13