Git Detached HEAD and Non-Fast-Forward Push Rejected
A detached HEAD records commits on no branch, and a rejected push protects commits you do not have. Recover with a branch and reflog; integrate before pushing.

Introduction & Quick Summary
Symptom. Two Git states that stop a day's work. After checking out a tag, a commit, or a PR ref, Git prints You are in 'detached HEAD' state. … If you want to create a new branch to retain commits you create, you may do so (now or later) by using -c with the switch command. Or a push is refused: ! [rejected] main -> main (non-fast-forward) with error: failed to push some refs … hint: Updates were rejected because the tip of your current branch is behind its remote counterpart.
Cause. Detached HEAD means HEAD points directly at a commit instead of at a branch ref. Anything you commit exists, but no branch records it, so the next git checkout moves HEAD away and the commits become unreachable from any ref. A non-fast-forward rejection means the remote branch has commits your local branch does not: pushing would make the remote lose them, so Git refuses until you integrate your work.
Fix. For a detached HEAD, create a branch before leaving — git switch -c rescue — and recover later work through git reflog. For the rejected push, fetch, inspect the divergence, integrate (git rebase origin/main, or git merge), then push. --force-with-lease is only for the case where you intentionally rewrote history and have confirmed the remote tip is still the one you expect.
Core Mechanics, Signatures & Reproducible Setup
Reproduce both in a scratch repository:
git init demo && cd demo
git commit --allow-empty -m "first"
git tag v1.0
git checkout v1.0 # detached HEAD: HEAD -> v1.0 commit, no branch
echo fix >> file.txt && git add . && git commit -m "hotfix" # commit on no branch
git switch main # hotfix is now reachable only through the reflog
git reflog # <sha> HEAD@{1}: commit: hotfix
git switch -c hotfix-branch <sha> # recover itAnd the rejected push:
# clone A pushes a commit; clone B still has the older tip
git push origin main # in A: fine
git push origin main # in B: rejected, non-fast-forward
git fetch origin
git log --oneline --graph --decorate HEAD origin/main
git rebase origin/main # replay B's work on top of A's commit
git push origin main # now fast-forwardThe decision at the divergence is the whole task: if your local commits are unpublished work, rebase or merge them onto the remote tip; if the remote commits are the ones you want to discard, that is a rewrite and needs the force family and a reason.
Key Comparison Table
| Situation | Command | Result |
|---|---|---|
| Detached, no new commits | git switch - or git switch main | Back to a branch, nothing lost |
| Detached, commits worth keeping | git switch -c rescue | Branch at the current commit |
| Left detached and switched away | git reflog, then git switch -c rescue <sha> | Recover from reflog |
| Refs gone entirely | git fsck --lost-found | Dangling commits in .git/lost-found |
| Unpublished local commits, remote advanced | git rebase origin/main | Linear history on top of remote |
| Local commits already pushed, remote advanced | git pull --rebase, then push | Clean push |
| Intentional rewrite | git push --force-with-lease | Overwrites only if remote unchanged |
| Remote is authoritative | git reset --hard origin/main | Discards local commits |
| Push rejection | Meaning | Correct response |
|---|---|---|
(non-fast-forward) | Remote has commits you lack | Fetch, rebase, push |
(fetch first) | Local ref missing entirely | git fetch, then inspect |
[remote rejected] … protected branch | Policy blocks direct push | Open a PR |
! [remote rejected] (stale info) | Someone else pushed first | git fetch and retry |
GH006: Protected branch update failed | Branch protection bypass missing | PR flow, not force |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Building from a tag and committing the fix there
Release builds check out a tag, so any hotfix is made detached. Create the branch first; the name is free and the commit becomes reachable:
git checkout v2.3.1
# edit
git switch -c hotfix/2.3.1 # branch at the current detached commit
git add -A && git commit -m "fix: guard null config"
git push -u origin hotfix/2.3.1The ordering matters: git switch -c before the commit also works, and is what the error message suggests, but doing it after the commit is equally safe as long as you have not left the commit.
2. Commits already lost after switching branches
git reflog records every movement of HEAD for 90 days by default (gc.reflogExpire), with unreachable objects kept for 30 (gc.reflogExpireUnreachable). Find the commit by message and take it into a branch — do not git reset first.
git reflog --date=iso | head -20
git show HEAD@{3} --stat
git switch -c recovered HEAD@{3}If the reflog has expired, git fsck --lost-found --unreachable lists dangling commits; git show <sha> identifies them by their diff.
3. Rebasing a branch that is already pushed
git rebase rewrites shas, so the remote copy is no longer an ancestor and the push is rejected again. That is expected: after rebasing your own feature branch, the correct push is --force-with-lease, and on a shared branch it is a pull request instead.
git fetch origin
git rebase origin/main
git push --force-with-lease origin feature/login # only if nobody else uses the branch--force-with-lease refuses if the remote ref is not what your origin/feature/login says — the guard against clobbering a colleague's push in the last few seconds.
4. When pull --rebase produces conflicts on every commit
A long-lived branch with many small commits replays badly. Squash first, or merge instead:
git fetch origin
git merge origin/main # one conflict resolution, merge commit
git push origin feature/login # fast-forward, no force neededMerging keeps the pushed history intact, so the push is a fast-forward and no force is required. The cost is a merge commit.
5. CI that force-pushes over the default branch
A workflow doing git push --force origin main after generating files will silently discard other people's commits. Use --force-with-lease at minimum, and better, only push generated output to a dedicated branch or a bot branch that a human merges:
- run: |
git config user.name "ci-bot"
git config user.email "ci@example.com"
git add -A
git commit -m "chore: regenerate" || exit 0
git push origin HEAD:bot/generated --force-with-lease6. Shallow clones in CI
actions/checkout defaults to fetch-depth: 1, so git describe, tag-based versioning, and rebases against origin/main fail with fatal: refusing to merge unrelated histories or shallow update not allowed. Fetch what the job needs:
git fetch --unshallow --tags origin
git fetch origin main:refs/remotes/origin/mainCommon Compilation/Runtime Mistakes & Version Gotchas
git checkout .to "reset". It discards unstaged changes in the working tree; when you meant to leave a detached HEAD, it is the wrong command in the same family.git reset --hard origin/mainas a habit. It deletes local commits with no reflog entry for the branch, and it is the most common way work is lost after a rejected push.- Plain
--force. It overwrites whatever is on the remote at that moment, including a colleague's commit pushed a second earlier.--force-with-lease(and--force-if-includeson newer Git) checks first. git switchvsgit checkout.git switch(2.23+) changes branches only and refuses ambiguous refs, which makes detached-HEAD mistakes rarer;git checkout <file>still means "restore file".pull.rebaseleft at the default. A merge-on-pull workflow turns every sync into a merge commit and every later rebase into a conflict marathon. Setgit config --global pull.rebase trueif your team rebases.- Tags are not branches.
git checkout v1.0is always detached by design;git checkout -B release/1.0 v1.0creates the branch and moves it. - Submodules report detached HEAD by default.
git submodule updatechecks out a commit, so edits inside a submodule have the same problem — branch before committing, then update the parent's gitlink.
Related tools. Compare the two sides of a divergence line by line before choosing rebase or reset with the text diff, hash the tree at HEAD@{1} and today's HEAD with the hash generator to confirm a recovery restored exactly the earlier tree, and decode the JSON payload of a Git hosting webhook or API response with the JSON formatter when a protected-branch rejection only names it by code.
Try matching browser tools
All toolsSmall utilities that fit Git work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Git guides
All Git guidesGit detected dubious ownership: Docker, Compose, and CI Fixes
A bind mount keeps the host UID and the container runs as root, so Git stops before reading a single object. Trust the path Git resolves, not the one you mounted.
Git config: Aliases, rerere, and Credential Helpers
Five config scopes decide one value at a time. Aliases are user-level shorthand, rerere records conflict resolutions, and credential helpers choose where your secret lives.
Git Hooks: pre-commit, commit-msg, and Husky Automation
Hooks live in .git/hooks, which a clone never receives, so core.hooksPath and Husky are how they travel. Exit codes abort the operation, and every hook is bypassable.
Git bisect: Binary Search, Automated Scripts, and Bug Hunting
Mark one bad and one good commit and Git halves the range each step. bisect run automates it through exit codes, and monotonicity is the assumption that must hold.
More in Git
All Git guidesThe guides filed next to this one in Git, in library order.