Vercel多子域名部署时如何实现manifest.json按子域动态适配
实现多子域名动态返回manifest.json的两种方案
两种方案都可以在Vercel环境正常运行,不需要额外的平台配置:
方案1:基于Next.js Rewrites的静态方案
适合manifest内容固定、不需要动态计算的场景,也就是你提到的rewrites方案,具体用法如下:
- 先在项目
public目录下新建manifests文件夹,按子域名命名存对应manifest文件,比如:public/manifests/app1.example.com.jsonpublic/manifests/app2.example.com.json
- 修改
next.config.js配置,添加rewrites规则:
/** @type {import('next').NextConfig} */ const nextConfig = { async rewrites() { return [ { source: '/manifest.json', has: [ { type: 'host', value: '(?<subdomain>.*).example.com', // 替换为你自己的根域名 }, ], destination: '/manifests/:subdomain.example.com.json', }, ] }, } module.exports = nextConfig
该规则会自动识别请求的子域名,返回对应命名的manifest文件。
方案2:基于API路由的动态方案
适合manifest需要动态生成、或者不想提前维护大量静态文件的场景:
- 新建API路由文件:
- Pages Router 路径:
pages/api/manifest.ts - App Router 路径:
app/api/manifest/route.ts
- Pages Router 路径:
- 写入逻辑代码(以Pages Router为例):
import type { NextApiRequest, NextApiResponse } from 'next' export default function handler(req: NextApiRequest, res: NextApiResponse) { const host = req.headers.host || '' let manifestContent // 按子域名匹配对应manifest内容 switch (host) { case 'app1.example.com': manifestContent = { name: '子应用1', short_name: '应用1', start_url: '/', display: 'standalone', theme_color: '#0070f3', // 其他manifest配置 } break case 'app2.example.com': manifestContent = { name: '子应用2', short_name: '应用2', start_url: '/', display: 'standalone', theme_color: '#f30070', // 其他manifest配置 } break default: manifestContent = { name: '默认应用', short_name: '默认应用', start_url: '/', } } // 设置正确的响应头 res.setHeader('Content-Type', 'application/manifest+json') res.setHeader('Cache-Control', 'public, max-age=86400') return res.status(200).json(manifestContent) }
- 在
next.config.js中添加rewrites规则,把manifest请求转发到API路由:
async rewrites() { return [ { source: '/manifest.json', destination: '/api/manifest', }, ] }
注意事项
- 本地测试时可以修改hosts文件,把不同子域名绑定到127.0.0.1验证规则是否生效
- Vercel部署前需要在项目控制台添加所有子域名作为自定义域名,确保请求能正确路由到你的项目
- 如果使用App Router,需要从
headers()函数中读取host字段,写法略有调整
内容的提问来源于stack exchange,提问作者Robert Wolf
相关产品推荐
相关产品推荐

