如何将GitHub Pages发布到自定义域名的子路径?
我完全理解你不想修改仓库名称,但希望将casbin-gui-editor的GitHub Pages内容发布到casbin.org/editor而非默认的casbin.org/casbin-gui-editor/的需求。这里有几个可行的方案,按推荐程度排序:
方案1:跨仓库部署到主Pages仓库的子目录(最优解)
这个方法的核心是把casbin-gui-editor构建后的产物,自动部署到你的主GitHub Pages仓库(casbin.github.io)的editor子目录下,这样主站点的casbin.org/editor就会直接加载编辑器内容,完全符合你的预期。
具体步骤:
- 在
casbin-gui-editor仓库中创建GitHub Actions工作流文件(路径示例:.github/workflows/deploy-to-editor.yml) - 编写工作流逻辑,完成以下操作:
- 拉取代码并安装项目依赖
- 构建项目(根据你的技术栈执行对应命令,比如
npm run build或yarn build) - 将构建产物目录(通常是
dist或build)的内容,推送到casbin.github.io仓库的editor文件夹中
示例工作流代码(假设是React/Vue类前端项目):
name: Deploy to casbin.org/editor on: push: branches: [ main ] # 替换为你的项目主分支名 jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Node.js uses: actions/setup-node@v4 with: node-version: '20' cache: 'npm' - name: Install dependencies run: npm ci - name: Build project run: npm run build - name: Deploy to casbin.github.io/editor uses: peaceiris/actions-gh-pages@v4 with: personal_token: ${{ secrets.PAGES_DEPLOY_TOKEN }} external_repository: casbin/casbin.github.io publish_dir: ./dist publish_branch: main # 主Pages仓库的托管分支 destination_dir: editor # 要部署到的子目录
- 在GitHub上生成一个Personal Access Token(PAT),勾选
repo权限,然后添加到casbin-gui-editor仓库的Secrets中,命名为PAGES_DEPLOY_TOKEN - 推送代码触发工作流,完成后访问
casbin.org/editor就能看到编辑器内容了
这个方案的优势是完全贴合你的需求,不需要修改任何仓库名称,且能实现自动部署,代码更新后编辑器内容会同步更新。
方案2:使用Cloudflare Page Rules做URL重写(依赖Cloudflare解析)
如果你的casbin.org域名是通过Cloudflare解析的,可以利用它的Page Rules功能实现URL重写,让访问casbin.org/editor的请求实际加载casbin.org/casbin-gui-editor/的内容,且浏览器地址栏保持casbin.org/editor不变,没有跳转痕迹。
具体步骤:
- 登录Cloudflare控制台,进入你的域名管理页面
- 转到Rules > Page Rules,创建新规则
- 设置URL匹配为
casbin.org/editor/* - 添加设置为Forwarding URL,选择Forwarding Type: Rewrite,目标URL设为
casbin.org/casbin-gui-editor/$1 - 保存规则并生效
这个方案不需要修改代码或仓库配置,但依赖Cloudflare的服务,适合已经用Cloudflare托管域名的场景。
方案3:修改项目基础路径+主仓库重定向(不推荐)
你可以在casbin-gui-editor项目中设置基础路径为/editor(比如React项目在package.json中添加"homepage": "/editor",Vue项目在vue.config.js中设置publicPath: '/editor'),然后在主casbin.github.io仓库中添加一个editor目录,里面放一个index.html做重定向到/casbin-gui-editor/。但这种方法会有跳转痕迹,体验不如前两种方案,仅作为备选。
内容的提问来源于stack exchange,提问作者hsluoyz

