Removing a committed secret from all Git history
git-filter-repo is the recommended tool for rewriting history: the git filter-branch manual says its use is not recommended and calls its performance glacially slow. Back up the repository first. Rewriting changes every affected commit hash, so a force-push replaces shared history: tell your teammates before you do it, and revoke the leaked key before anything else, because old clones keep the secret.
Scope: erasing a secret from past commits. Why a plain delete fails is page 16, and the steps before rewriting, revoking and scanning, are page 18.
How do I remove a committed secret from all Git history?
Run git filter-repo --invert-paths --path .env on a fresh clone, then force-push. Revoke the key first.
What if git-filter-repo is not installed?
git filter-branch ships with Git and does the same job more slowly. The tested run below uses it. Afterwards delete the refs/original backup refs and expire the reflog, or the old commits stay reachable.
Tested commands and output
Command: git filter-branch --index-filter "git rm --cached --ignore-unmatch -q .env" -- --all
$ git log --all -Ssk-test-FAKE123 --oneline
ecfa43c add-env
$ git filter-branch -f --index-filter "git rm --cached --ignore-unmatch -q .env" -- --all
Rewrite ecfa43c5b128985f839a5717ad54db1fea4a3bf6 (1/2) (0 seconds passed, remaining 0 predicted)
Rewrite 6fd50d7de30c6a1eafe6b8ae0a2c5986fed3274b (2/2) (0 seconds passed, remaining 0 predicted)
Ref 'refs/heads/main' was rewritten
$ git for-each-ref --format="%(refname)" refs/original | xargs -n1 git update-ref -d
$ git reflog expire --expire=now --all
$ git gc -q --prune=now
$ git log --all -Ssk-test-FAKE123 --oneline | wc -l
0
$ git log --oneline
cf87f6b second
940b274 add-envNote
The count of 0 means no commit still contains the key. Force-push with git push --force-with-lease only after teammates agree, and expect them to re-clone.
Source: https://github.com/newren/git-filter-repo (git-filter-repo project page) Source: https://git-scm.com/docs/git-filter-branch (git filter-branch docs) Source: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository (GitHub guide to removing sensitive data)
Full kit: Secrets Safety Kit