解决 Git 报错 failed to push some refs to 且提示 non-fast-forward
深入分析 Git 提交推送报错 non-fast-forward 根因,掌握 git pull --rebase 与冲突解决的标准协同流程。
问题现象
在本地完成代码编写并提交后,执行 git push origin main 时推送被远程仓库直接拒绝:
To https://github.com/example/repo.git
! [rejected] main -> main (non-fast-forward)
error: failed to push some refs to 'https://github.com/example/repo.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
本地提交无法同步到远端,协作流程受阻。
触发根因
Non-fast-forward(非快进合并)是 Git 为防止协作者代码被静默覆盖而设计的核心保护机制:
- 远程分支存在本地未包含的新提交:在您从远端拉取代码之后、本次推送之前,团队其他成员已经向该远程分支推送了新的 commit。
- 此时远端分支的 HEAD 已经前进,而本地分支的分叉起点落后于远端最新节点。如果 Git 允许您直接 push,远端其他同事刚刚合入的代码就会被物理覆盖抹杀。
- 因此 Git 强制拒绝推送,要求您必须先将远端的最新提交拉取到本地完成合并或变基,方可继续推送。
诊断排查步骤
1. 查看本地分支与远程追踪分支的领先/落后状态
git fetch origin
git status
输出示例:
On branch main
Your branch and 'origin/main' have diverged,
and have 1 and 2 different commits each, respectively.
提示本地领先 1 个提交,同时落后远端 2 个提交,确认发生了分支分叉。
解决方案
方案一:使用 git pull --rebase 优雅拉取远端变更(强烈推荐)
推荐采用变基(Rebase)模式同步,可以避免产生多余且混乱的“Merge branch ...”提交节点,保持 Git 提交历史呈整洁的直线拓扑:
# 拉取远端更新并将本地新提交按顺序重新嫁接在远端之后
git pull --rebase origin main
- 若无文件冲突,Git 会自动完成变基。
- 若存在代码冲突,Git 会暂停并标记冲突文件,手动修改保留正确代码后:
# 标记冲突已解决 git add <conflicted-file> # 继续完成变基 git rebase --continue
变基完成后,再次推送:
git push origin main
方案二:使用标准 git pull 生成 Merge Commit(保守合并)
如果不习惯 rebase,使用传统合并:
git pull origin main
解决可能出现的冲突文件并完成提交:
git commit -m "Merge remote-tracking branch 'origin/main'"
git push origin main
方案三:个人特性分支上的强制推送(谨慎操作)
如果您是在自己专用的特性分支(Feature Branch)上进行了本地 commit 历史重构(如 git commit --amend 或本地交互式 rebase),且确认该分支没有其他协作者:
使用带租约的更安全强制推送:
git push --force-with-lease origin feature-my-branch
警告:严禁在
main、master或共享生产分支上使用任何--force操作!
验证方法
执行推送后查看状态:
git status
输出显示:
On branch main
Your branch is up to date with 'origin/main'.
nothing to commit, working tree clean
本地与远程仓库完美对齐,问题排除。


