Remove .env from git history (rotate first)
How to check$ git log --all --oneline -- .env
a1b2c3d add env
# any output means .env is in your history
Rotate every key in the file first. Rewriting history doesn't un-leak anything: forks, clones and caches keep the old values. Then stop tracking .env, and rewrite history only if you still need to.
Why it happens
Deleting .env in a new commit removes it from the latest version only. Every earlier commit still contains it, and anyone with a clone or fork has those commits. GitHub's guide says that if the data is a secret, the first step is to revoke or rotate it, and that this may be enough on its own.
Fix it by hand
- Rotate every secret in the file. Database passwords, API keys, auth secrets: all of them. Update your host and CI with the new values and redeploy.
- Stop tracking the file without deleting your local copy, and ignore it going forward:
git rm --cached .env printf '.env*\n!.env.example\n' >> .gitignore git add .gitignore git commit -m "Stop tracking .env" - If you still need history cleaned, install git-filter-repo version 2.47 or later (it needs the
--sensitive-data-removalflag), make a fresh clone, and run:
Add anothergit-filter-repo --sensitive-data-removal --invert-paths --path .env--pathfor each other place the file lived. - Verify, then force-push.
git log --all -- .envshould print nothing. Then:
This changes the hash of every later commit and can't be undone after the push.git push --force --mirror origin - Clean up what you can't rewrite. On GitHub, contact Support to remove cached views and pull request references. Ask collaborators to delete old clones and re-clone. Forks keep the data; GitHub can't clean them for you.
Stop it happening again
- Ignore
.env*from the first commit, and keep a committed.env.examplewith placeholder values. - Turn on secret push protection for the repository.
- Ask your agent to run a secret check before every commit that touches config.
Key Leaked $7
Key Leaked scans every commit on every branch, tag and stash, finds keys you removed from the code that are still in history, ranks them by danger, and shows the exact git-filter-repo commands. It never rewrites history itself, and it puts rotation first.
- Finds every secret in your files, every commit on every branch, and the JavaScript you ship to browsers.
- Gives exact revoke-and-replace steps for 19 providers, and never prints your full secrets.
- Verdict first. Every finding shows the file and line, what it breaks, and the fix as a diff that is applied only with your OK.
Key Leaked: how it works, with examples · Install guide
Works with Claude Code, Claude.ai, Cursor, Codex and other agents that read SKILL.md files. No installs, no accounts, works offline. No-questions refund.