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:

  1. 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.
  2. Find the commit hash using git log --oneline or your preferred Git GUI/editor for the commit with secret (the earliest commit).
  3. Start an interactive rebase
git rebase -i <hash>~1

Replace <hash> with the hash of the commit you want to remove first.

  1. Mark commits to remove: Change pick to drop for the commits you want to erase. In this example, you would drop commit 1 and commit 7. Advanced users can change pick to edit but will have more things to do.
  2. Save and exit the editor:

Git will then replay the remaining commits without the dropped commits.

  1. Force push the changes to update the remote repository:
git push --force

Done! The commits exposing secrets are now removed from your Git history.