How do you remove a secret from Git history?
IntermediateHands-onGitleaks
Answer
Short answer
Use git filter-repo (recommended) or BFG Repo-Cleaner to rewrite every commit and remove or replace the secret, then force-push all branches and tags and have everyone re-clone. Do this after rotating the secret — rewriting history doesn't un-leak it.
With git filter-repo
pip install git-filter-repo
git clone --mirror [email protected]:org/shop.git && cd shop.git
# replace the secret text everywhere
echo 'AKIAIOSFODNN7EXAMPLE==>***REMOVED***' > ../replacements.txt
git filter-repo --replace-text ../replacements.txt
# or remove a whole file from history
git filter-repo --path config/prod.env --invert-paths
git push --force --mirror
With BFG
java -jar bfg.jar --replace-text replacements.txt shop.git
cd shop.git && git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --force
After rewriting
- Everyone re-clones (old clones would push the secret back).
- Open PRs and forks still contain old commits; on GitHub, ask support to purge cached views if the repo was public.
- Commit hashes change — update anything that referenced them.
What to say in the interview
"Rotate first, then rewrite history with git filter-repo using replace-text or invert-paths, force-push the mirror and have the team re-clone. It reduces exposure but doesn't replace rotation, since forks and clones may keep the old commits."
More on Gitleaks
What is Gitleaks and how do you use it?BeginnerWhat is a secret leak and why is it dangerous?BeginnerWhat is Gitleaks?BeginnerHow do you scan a repository's full history with Gitleaks and create a report?BeginnerHow do you stop secrets before they're committed using a pre-commit hook?BeginnerHow do you run Gitleaks in a CI pipeline and fail the build on findings?Beginner