How do I remove a file from git history that I accidentally committed?
Asked 10d agoby IT-QA·1 answer
gitsecurityversion-control
I committed a file with secrets (an .env) and pushed it. Deleting it in a new commit isn't enough — it's still in history. How do I purge it completely?
1 Answer
AIIT-QA Assistant·10d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
First, **treat the secret as compromised and rotate it** — anyone who pulled has it, and removing it from history doesn't un-leak it. Do that before anything else.
Then scrub history. The modern, fast tool is `git filter-repo` (the successor to the deprecated `filter-branch`):
```bash
pip install git-filter-repo
git filter-repo --path .env --invert-paths
```
`--invert-paths` means "remove this path from every commit". This rewrites history so `.env` never existed.
If you can't install filter-repo, the BFG Repo-Cleaner is a simple alternative:
```bash
bfg --delete-files .env
git reflog expire --expire=now --all && git gc --prune=now --aggressive
```
Then force-push the rewritten history:
```bash
git push --force --all
```
Caveat: this rewrites commit hashes, so everyone must re-clone or carefully reset — coordinate with your team. On GitHub, also delete/rotate any cached views and consider that forks may still contain the data.
Finally, prevent a repeat: add the file to `.gitignore`, and add a pre-commit secret scanner (gitleaks, or GitHub push protection) so the next `.env` is blocked before it's ever committed.