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

Vercel站点配置GitHub Pages反向代理时出现自动重定向问题求助

Vercel Rewrite代理GitHub Pages时跳转而非原URL展示的问题解决

问题原因

GitHub Pages服务器默认会对部分请求返回强制重定向响应(比如请求路径未带末尾斜杠、或涉及自定义域名的匹配逻辑),即便你在Vercel配置的是rewrite而非redirect,当源服务器返回3xx状态码+Location头时,浏览器会直接执行跳转,而非保留原域名展示内容。

解决方案

1. 先验证GitHub Pages的跳转行为

用curl命令检查目标URL的响应头,确认是否存在跳转:

curl -I https://example.github.io/docs/your-test-path

如果返回301/302状态码且带有Location字段,说明确实是GitHub Pages主动发起了跳转。

2. 修改Vercel配置覆盖跳转头

在vercel.json的rewrite规则中添加headers配置,清空或覆盖GitHub Pages返回的Location头:

{
  "source": "/docs/:path+",
  "destination": "https://example.github.io/docs/:path",
  "headers": {
    "Location": ""
  }
}

这种方法适合简单场景,直接在代理时抹除跳转指令。

3. 使用Edge Functions手动处理响应

如果上述配置无效,用Vercel Edge Functions接管请求,手动获取并修改GitHub Pages的响应:
创建项目根目录下的middleware.js文件:

import { NextResponse } from 'next/server';

export async function middleware(request) {
  const url = request.nextUrl;
  if (url.pathname.startsWith('/docs/')) {
    // 构造GitHub Pages的目标URL
    const targetPath = url.pathname.replace('/docs/', '');
    const targetUrl = new URL(`https://example.github.io/docs/${targetPath}`);
    
    // 发起请求并获取响应
    const response = await fetch(targetUrl);
    // 复制响应并删除Location头
    const modifiedResponse = new NextResponse(response.body, response);
    modifiedResponse.headers.delete('Location');
    
    return modifiedResponse;
  }
  return NextResponse.next();
}

这种方式更灵活,还能处理其他可能的响应头问题。

4. 检查GitHub Pages内容的资源路径

确保GitHub Pages上的文档资源(图片、链接、脚本)都使用相对路径,而非硬编码的https://example.github.io绝对路径,否则即便代理成功,页面内的资源也会跳转到GitHub域名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 07:12:40