How to remove all commit history from a Git branch and rebuild it
Sometimes you accidentally commit sensitive data and need to completely remove the commit history of a branch.
The safest way to do this is by recreating the branch as an orphan branch, which removes all previous commits while keeping the current files.
This approach works for any branch (main, bleeding-edge, legacy, etc.).
Steps
Note
These steps assume the branch is named
main. Replace it with your branch name if needed.
First, check out the branch you want to clean:
git checkout main
Create an orphan branch (no history, working tree unchanged):
git checkout --orphan main-clean
Commit the current state as the new starting point:
git add .
git commit -m "cleanup"
Replace the old branch and force-push it:
git branch -D main
git branch -m main-clean main
git push origin main --force
After this, the branch will contain only one commit, and the previous history will no longer be referenced by the branch.
Warning
If secrets were ever committed, rotate them anyway.
Rewriting history reduces exposure but cannot remove copies that already exist in forks or local clones.
Cheers.