核心结论:禁止强制推送必须在代码托管平台(GitHub/GitLab)的仓库设置中配置 Protected Branches,本地 Git 命令无法单方面生效。
- 适用场景:团队协作的主干分支(main/master)或生产环境分支
- 前置条件:确认拥有仓库管理员(Admin)或维护者(Maintainer)权限
- 验证方式:配置后尝试 force push,服务端应返回拒绝错误
技术原理:为何本地配置无效
Git 是分布式版本控制系统,本地仓库与远程仓库地位平等。本地配置的钩子(hooks)或 config 只能约束本地操作,无法约束其他人推送到远程服务器。要禁止 force push,必须在存储代码的中心服务器(即托管平台)上设置策略,让服务器在接收推送时拒绝非快进(non-fast-forward)的请求。
平台配置实操:GitHub 与 GitLab
GitHub 配置步骤:
- 进入仓库页面,点击顶部 Settings 标签。
- 左侧菜单选择 Branches。
- 点击 Add branch protection rule。
- 在 Branch name pattern 输入分支名(如 main 或 master)。
- 确保不要勾选 Allow force pushes(允许强制推送)。
- 点击 Create 保存。
GitLab 配置步骤:
- 进入项目页面,左侧菜单选择 Settings -> Repository。
- 展开 Protected branches 部分。
- 在 Branch 下拉框选择要保护的分支。
- Allowed to push 设置为 No one 或 Maintainers。
- 确保 Allow force push 复选框未被勾选。
- 点击 Protect 保存。
验证配置是否生效
配置完成后,在本地终端尝试对该分支执行强制推送命令。如果配置生效,远程仓库会返回错误信息,拒绝推送。
测试命令:
git push `--force` origin <branch-name>
预期结果:终端显示 rejected 或 error,提示 remote rejected 或 pre-receive hook declined,说明服务端拦截了请求。
配置注意事项与误区
- 管理员权限 bypass:仓库管理员通常可以绕过保护规则,不要误以为配置后绝对安全。
- 已有历史分歧:如果分支已经存在历史分歧,开启保护前可能需要先协调一致,否则后续合并会受阻。
- 本地配置误解:本地 git config receive.denyNonFastForwards 仅影响本地作为服务器时的行为,对远程仓库无效。
参考来源
- GitHub Docs: About protected branches - https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches
- GitLab Docs: Protected branches - https://docs.gitlab.com/ee/user/project/protected_branches.html
原文链接:https://www.zjcp.cc/ask/11134.html
