How to Remove a Commit That Exposes Secrets from Git History
Updated: 30th September 2025
Tags: git
If you’re not comfortable using Vim, you can set another editor like Nano first:
git config --global core.editor "nano"
Imagine a situation where you accidentally committed a secret, and then made 100 more commits afterward.
Fortunately, the secret was only in a single file and committed in one commit (let’s call it commit 1). However, you also made another change to that same file in commit 7. Here’s how to safely remove both commits from history:
- Backup your file(s) that contain the secret and were modified in commit 1 and 7, in case something goes wrong or you don’t have an editor with local history.
- Find the commit hash using
git log --onelineor your preferred Git GUI/editor for the commit with secret (the earliest commit). - Start an interactive rebase
git rebase -i <hash>~1
Replace <hash> with the hash of the commit you want to remove first.
- Mark commits to remove: Change
picktodropfor the commits you want to erase. In this example, you would drop commit 1 and commit 7. Advanced users can changepicktoeditbut will have more things to do. - Save and exit the editor:
- In Nano, press
Ctrl+X, thenYto confirm. - In Vim, press
Esc, then type:wqand hit Enter. If doesn’t work, abort and change editor to nano as I said in first sentence and start again :P
Git will then replay the remaining commits without the dropped commits.
- Force push the changes to update the remote repository:
git push --force
Done! The commits exposing secrets are now removed from your Git history.