To remove a secret from git history, first revoke or rotate the credential, because once it has been pushed you must assume it is compromised and no rewrite can un-leak it. Then rewrite history with git filter-repo --sensitive-data-removal (deleting the file with --invert-paths --path, or scrubbing the string with --replace-text), force-push every ref with git push --force --mirror origin, have every collaborator re-clone, and on GitHub contact Support to purge cached views and pull-request refs that a force push cannot touch.

This guide walks through each step with the exact commands, and the output shown comes from a throwaway repository I built and cleaned with git 2.54 and git-filter-repo 2.47.0 in December 2026. It also covers BFG Repo-Cleaner, the GitHub-specific parts most guides skip (PR refs, forks, Support requests, push protection and secret scanning alerts), and how to scan history with gitleaks and TruffleHog so you find every copy before you start.

Step 1: Rotate the secret before you touch git history

GitHub's own guide to removing sensitive data puts this first: if the data is a credential, revoke or rotate it, and once it can no longer be used, that may be all you need to do. That ordering is not bureaucratic caution; it reflects how leaks actually play out:

  • Public repositories are scanned continuously. On GitHub, secret scanning runs automatically for free on public repositories and, for partner token types, the provider is notified "so they can take action, such as revoking the credential." Other people's scanners are just as quick and much less friendly.
  • Every existing clone, fork, CI cache, and mirror already has the old objects. A rewrite only changes the copies you control.
  • A history rewrite takes coordination and can take days if Support is involved. Rotation takes minutes.

Do the rotation in this order:

  1. Issue a replacement credential and deploy it (secret manager, CI variables, environment).
  2. Revoke the leaked one. For an AWS access key, for example: aws iam create-access-key --user-name app-deployer, update consumers, then aws iam delete-access-key --user-name app-deployer --access-key-id AKIA....
  3. Check the provider's logs for use of the leaked credential between the leak and the revocation (CloudTrail for AWS, the audit log for GitHub tokens, the dashboard request logs for Stripe and similar). If you find unexpected use, you now have an incident, not a cleanup; the containment order in our compromised npm package runbook (isolate first, then rotate from a clean machine) applies to any leaked credential.

If the credential was a long-lived cloud key used by CI, this is also the moment to remove the need for it entirely; our GitHub Actions OIDC guide shows how to deploy to AWS, GCP and Azure with short-lived tokens instead.

Do you even need to rewrite history?

After rotation, the leaked value is a dead string. Rewriting is still worth doing when:

  • the data is not a rotatable credential (customer data, a private key you cannot reissue quickly, internal hostnames you consider sensitive);
  • compliance or a customer requires that it be purged;
  • the repository is private and you want to keep history clean before opening it up.

If the secret is only in your latest local commit and has not been pushed, you do not need any of this; amend or reset the commit as shown in our guide to undoing git commits.

Step 2: Find every copy of the secret in history

Before rewriting, find every file, path and commit that contains the secret, so the rewrite catches all of them. Secrets get copied: into a renamed file, a test fixture, a docs example.

With plain git, the pickaxe option finds commits that add or remove a string:

# Commits where the string was added or removed, on all refs
git log --all --oneline -S 'sk_live_51FAKE'

# Same, with the patch, to see the paths involved
git log --all -p -S 'sk_live_51FAKE'

# Every historical path a file has lived at (renames)
git log --all --name-status --follow -- .env

In my demo repository, the pickaxe search showed the .env file being added in one commit and untracked in a later one, which is the classic pattern: someone notices, adds .env to .gitignore, runs git rm --cached, and assumes the problem is solved while the secret stays in every earlier commit.

$ git log --all -p -S 'sk_live_' --oneline
fd2c655 stop tracking .env
diff --git a/.env b/.env
deleted file mode 100644
--- a/.env
+++ /dev/null
-STRIPE_KEY=sk_live_51FAKEFAKEFAKEFAKE1234567890abcdef
89cc4ac add config
diff --git a/.env b/.env
new file mode 100644
+++ b/.env
+STRIPE_KEY=sk_live_51FAKEFAKEFAKEFAKE1234567890abcdef

Scan with gitleaks and TruffleHog

Pattern scanners find secrets you did not know about, which is useful because a leak rarely comes alone. Gitleaks scans git log -p output; since v8.19.0 the git subcommand replaced the older detect and protect commands, according to the gitleaks README. The current release is v8.30.1.

# Scan full history of all refs, write a JSON report
gitleaks git -v --log-opts="--all" --report-path gitleaks.json --report-format json .

TruffleHog (v3.100.1 at the time of writing) adds verification: for detectors that support it, it tries the credential against the provider's API and labels results verified, unverified or unknown. That tells you whether rotation actually worked.

# Local repository, only live or unverifiable findings
trufflehog git file://. --results=verified,unknown

# A GitHub repository, including issue and PR comments
trufflehog github --repo=https://github.com/OWNER/REPO --issue-comments --pr-comments

Run TruffleHog again after rotation: the leaked key should drop from "verified" to "unverified." If it is still verified, the revocation did not take.

Step 3: Rewrite history with git filter-repo

git filter-repo is the tool both the Git project's documentation and GitHub recommend for history rewrites, replacing the old git filter-branch. GitHub's guide requires version 2.47 or later because that release added --sensitive-data-removal, which fetches every ref from the remote (including refs/pull/* where possible), tracks which refs changed, and prints the information GitHub Support needs.

Install it with your package manager, or into an isolated Python environment:

brew install git-filter-repo          # macOS / Linuxbrew
# or, in a venv (it is a single Python script)
python3 -m venv ~/.venvs/filter-repo && ~/.venvs/filter-repo/bin/pip install git-filter-repo
git filter-repo --version

Work in a fresh clone, not your day-to-day working copy. filter-repo refuses to run on a non-fresh clone by default, and you want a copy you can throw away if the result is wrong.

git clone https://github.com/OWNER/REPO.git repo-clean
cd repo-clean

Remove a whole file from every commit

Use --invert-paths with the full path inside the repository. Add one --path per historical location if the file was renamed or copied.

git filter-repo --sensitive-data-removal --invert-paths --path .env

Real output from the demo repository:

NOTICE: Fetching all refs from origin to make sure we rewrite
        all history that may reference the sensitive data, via
      git fetch -q --prune --update-head-ok --refmap "" origin +refs/*:refs/*
Parsed 6 commits
New history written in 0.11 seconds; now repacking/cleaning...
You rewrote 5 (of 6) commits.

NOTE: First Changed Commit(s) is/are:
  89cc4ac25f5644f74b323fae3d0cf3eaf73306e2
NOTE: LFS object orphaning not checked (LFS not in use)

Save the "First Changed Commit(s)" line; GitHub Support asks for it.

Replace a secret string everywhere it appears

When the secret sits inside a file you want to keep (a config module, a notebook, a test), replace the value instead of deleting the file. Create an expressions file outside the repository. Each line is a literal string or a regex: pattern, optionally followed by ==> and a replacement (the default replacement is ***REMOVED***):

sk_live_51FAKEFAKEFAKEFAKE1234567890abcdef==>***REMOVED***
regex:ghp_[A-Za-z0-9]{36}==>***REMOVED***
git filter-repo --sensitive-data-removal --replace-text ../replacements.txt

After the run, the historical version of config.py reads API_TOKEN = "***REMOVED***" in every commit, while the current version (which already read from the environment) is untouched. You can chain several filter-repo invocations in the same clone, as I did here; the "next steps" it prints tell you to ignore them until the final run.

Keep that replacements file out of the repository and delete it afterwards. It contains the very secrets you are purging.

Verify before you push

# Should print nothing
git log --all -p | grep -E 'sk_live_|ghp_'
git rev-list --all | xargs git grep -l -E 'sk_live_|ghp_'

# Refs that will change on the server, and how many PR refs are affected
cat .git/filter-repo/changed-refs
grep -c '^refs/pull/.*/head$' .git/filter-repo/changed-refs

In my run both searches came back empty, and changed-refs listed refs/heads/feature/x, refs/heads/main and refs/tags/v1.0. Re-run gitleaks on the clean clone too. If the PR count is far higher than you expected, stop: until you push, you can still delete this clone and walk away.

The BFG Repo-Cleaner alternative

BFG Repo-Cleaner (current release 1.15.0, needs Java 11 or newer) is still popular for simple jobs and is very fast. Its workflow uses a mirror clone and then requires you to expire reflogs and garbage-collect yourself:

git clone --mirror https://github.com/OWNER/REPO.git
java -jar bfg-1.15.0.jar --delete-files .env REPO.git
java -jar bfg-1.15.0.jar --replace-text replacements.txt REPO.git
cd REPO.git
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --force

The gotcha: by default BFG protects your latest commit on HEAD and will not change its contents, so you must first commit a version that no longer contains the secret. I prefer filter-repo for secrets because --sensitive-data-removal handles ref fetching and produces the commit IDs GitHub Support needs; BFG is fine for removing large blobs.

git filter-repo BFG Repo-Cleaner
Install Python script (brew, pip, distro package) Java 11+ JAR
Delete files by path --invert-paths --path a/b/.env (exact paths) --delete-files .env (by file name, any directory)
Replace strings --replace-text with literals and regex --replace-text with literals and regex
Latest commit Rewritten like the rest Protected by default
Sensitive-data helpers Fetches all refs, lists changed refs, prints first changed commits, LFS orphan check None; manual reflog expire and gc
Recommended by GitHub docs Yes Not mentioned in the current guide

Step 4: Force-push the rewritten history

Push every ref, overwriting the server's copies:

git push --force --mirror origin
 + d7b343d...a2ff501 feature/x -> feature/x (forced update)
 + 22fcc29...537fd82 main -> main (forced update)
 + 22fcc29...537fd82 v1.0 -> v1.0 (forced update)

On GitHub, pushes to refs/pull/* are rejected because those refs are read-only; that is expected. If any other ref fails, branch protection or rulesets are usually the cause: temporarily allow force pushes for the affected branches, push again, and restore the protection immediately.

Why the force push is not the end

Here is the uncomfortable part, which I confirmed on the demo's server-side bare repository. After the force push, no branch or tag references the old commits, but the objects are still in the server's object store until it garbage-collects them:

$ git -C origin.git show 89cc4ac:.env
DB_URL=postgres://localhost/app
STRIPE_KEY=sk_live_51FAKEFAKEFAKEFAKE1234567890abcdef

On a hosting service, that translates to old commit URLs that still render if someone knows the SHA, pull request diffs that still show the secret, and forks that carry the full old history. That is why rotation came first.

Step 5: GitHub-specific cleanup

GitHub's guide spells out what is left after your force push and what Support will and will not do.

Pull requests. Your push cannot change refs/pull/*. Closed PRs that touched the rewritten history keep referencing the old commits. GitHub Support can either delete the affected PRs entirely or dereference them, keeping descriptions and comments but making the old diffs inaccessible. Dereferencing does not remove the secret if someone pasted it into a comment, so edit or delete those comments yourself.

What to send Support. Through the GitHub Support portal, provide the owner and repository name, the number of affected PRs (the grep -c count above), the "First Changed Commit(s)" from the filter-repo output, and, if filter-repo reported "LFS Objects Orphaned by this rewrite", that fact plus the file it names. Support then handles PR dereferencing or deletion, server-side garbage collection, removal of cached views, and orphaned LFS objects.

Support's conditions. Support only proceeds once every non-PR reference is clean and no forks still contain the data, and it only assists with sensitive data when the risk cannot be mitigated by rotating credentials. In other words, a rotated API key alone may not qualify; personal data or an unrotatable key will.

Forks. GitHub treats forks as outside its control. Ask fork owners to delete their forks or apply the same cleanup.

Secret scanning alerts. If GitHub raised an alert, close it with the "revoked" resolution once rotation is done, so the record shows what happened. Do not count on the rewrite closing the alert for you; resolve it explicitly.

Step 6: Get collaborators onto the new history

The most common way a purged secret comes back is a teammate with an old clone running git pull and git push. GitHub's guidance:

  • The simplest safe instruction is: delete your clone and re-clone.
  • Anyone with unpushed work on an old branch must rebase it onto the new history rather than merge, because a merge reintroduces the old commits.
  • The filter-repo manual's "Sensitive Data Removal" discussion describes the longer procedure for cleaning a clone in place, using the First Changed Commit(s).

Do it in this order: announce a freeze on the affected branches, do the rewrite and push, then send the re-clone instructions. Anyone who pushes during the window forces you to redo the rewrite or lose their work. CI caches, build servers with persistent workspaces, and internal mirrors are "collaborators" too; clear them.

Also expect side effects: every commit after the first changed commit has a new SHA, so links to commits in issues or chat break, signed commits lose their signatures, and open PRs should be merged or closed before you start.

Step 7: Stop the next leak

  • Push protection. For GitHub user accounts, push protection is on by default and stops you pushing supported secrets to public repositories. Repository-level push protection is off by default and requires GitHub Secret Protection for private repositories; turn it on, and limit who can bypass it.
  • Pre-commit scanning. Gitleaks ships a pre-commit hook; pin the current release in .pre-commit-config.yaml:
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.30.1
    hooks:
      - id: gitleaks
  • CI scanning on every PR. Run TruffleHog with --since-commit set to your default branch so each PR is checked only for new findings.
  • No secrets in files at all. Keep .env in .gitignore from the first commit, commit a .env.example with placeholders, and load real values from a secret manager or your CI's secret store. For publishing pipelines, tokenless approaches such as npm trusted publishing remove a whole class of long-lived tokens that could leak.
  • Review before committing. git diff --cached before every commit, and avoid git add . in repositories that have local config files.

Frequently Asked Questions

Does deleting the file in a new commit remove the secret from git?

No. A new commit that deletes .env only changes the latest snapshot; every earlier commit still contains the file, and git log -p or a checkout of an old commit shows it. You must rotate the secret and, if needed, rewrite history.

Is git filter-repo better than BFG for removing secrets?

For secrets, yes in most cases. git filter-repo --sensitive-data-removal fetches all refs, rewrites the latest commit too, records changed refs and prints the first changed commits GitHub Support asks for. BFG is fast and simple, but protects the HEAD commit by default and needs manual reflog expiry and garbage collection.

Will a force push remove the secret from GitHub completely?

No. Old commits stay reachable by SHA in cached views and pull request refs until GitHub garbage-collects them, and forks and existing clones keep the full old history. Contact GitHub Support for PR refs and cached views, ask fork owners to clean up, and rely on rotation for actual safety.

What if the secret was in a public repository for only a few minutes?

Treat it as compromised. Automated scanners watch public pushes continuously, and for supported token types GitHub notifies the provider through its secret scanning partner program. Rotate immediately, check the provider's access logs, then decide whether a rewrite is still worth doing.

How do I remove a secret from git history without rewriting every commit hash?

You cannot. Git commit IDs are hashes of their content and their parents, so changing any commit changes it and every descendant. If changing hashes is unacceptable, rotate the secret and leave history alone; a revoked credential in history is harmless.

How do teammates update their clones after a history rewrite?

Ideally they delete the clone and re-clone. Anyone with unpushed work should rebase those commits onto the new history instead of merging, then delete the old clone. Never pull the rewritten branch into an old clone and push, as that brings the secret back.

Conclusion

Rotate first, then decide whether the rewrite is worth it. When it is, scan with gitleaks and TruffleHog to find every copy, run git filter-repo --sensitive-data-removal in a fresh clone, verify, git push --force --mirror, get Support to purge PR refs and cached views on GitHub, and make every collaborator re-clone. Then switch on push protection and a pre-commit scanner so you never have to do it again.