Help, I committed a password or API key
Revoke the secret first, then get it out of your history. What that takes depends on whether you pushed.
The fix
Revoke or rotate the secret anyway if there is any chance it left your machine.
git rm --cached .envTakes the file out of Git, but keeps it on your disk.
printf "\n.env\n" >> .gitignoreAdds the file to
.gitignoreon a line of its own, so Git ignores it from now on.git add .gitignoreStage the new ignore rule.
git commit --amend --no-editRewrites the last commit without the file. Only enough if the file came in with that commit:
git log --oneline -- .envshould list exactly one commit, the same onegit log --oneline -1shows.
.env is an example. Replace it with your own.
Revoke the key and create a new one, right now. Bots scan public repositories for keys within minutes.
git clone https://github.com/you/my-app.git my-app-cleanfilter-repo only works on a fresh clone, so make one. Your current folder stays untouched as a backup.
cd my-app-cleanWork in the fresh clone from here.
git filter-repo --path .env --invert-pathsRemoves the file from every commit.
git filter-repois a separate tool (pip install git-filter-repo). It removes theoriginremote on purpose.git remote add origin https://github.com/you/my-app.gitConnect the remote again.
git push --force origin --allOverwrites every branch on the remote with the cleaned history. Protected branches need an admin to allow this.
Rewrites pushed historygit push --force origin --tagsThe same for tags.
Rewrites pushed historyEveryone on the team clones again, or an old clone brings the file back. Copy your
.envinto the new clone and add it to.gitignore.
https://github.com/you/my-app.git is an example. Replace it with your own.
Revoke the key or change the password first. Once it has been pushed, treat it as public, even after you clean the history.
Why this works
Removing a file in a new commit is not enough: every older commit still contains it. That is why the fix either rewrites the last commit (before pushing) or every commit (after pushing). But rewriting history cannot take back what has been public: clones, forks and bots that scan new commits for keys may already have it. Revoking the key is the real fix; the history cleanup only stops it from spreading further.