Question

How do I remove a file containing secrets from Git history?

Vault Verified
Curated Intelligence
Definitive Source
Answer

Start with the part people skip: if a credential was pushed anywhere others could read it, treat it as compromised and rotate it first. Rewriting history removes the file from the repository, but it cannot un-read anything already cloned, forked, cached by a hosting provider, or picked up by an automated scanner. Rotation is the fix; history rewriting is cleanup.

Deleting the file in a new commit is not sufficient, because every earlier commit still contains it and anyone can check out those commits. The content has to be removed from the commits themselves, which means rewriting them.

The recommended approach is a purpose-built history rewriting tool, which is considerably faster and safer than the built-in branch filter older instructions suggest. It removes the specified paths from every commit and rewrites the affected history.

Several consequences follow, and they are why this is disruptive rather than routine.

  • Every rewritten commit gets a new hash, so the rewritten branch and the original have diverged completely and pushing requires force.
  • Everyone else must re-clone or reset to the rewritten history. Merging an old clone back in reintroduces the very commits you removed, which is a common way for this to fail after the fact.
  • Open pull requests, tags and any references built on the old commits need attention.
  • Hosting providers often keep unreachable objects accessible for a period, so you may need to ask them to run garbage collection.

Take a full backup clone before starting, because the operation is not reversible in place.

The durable prevention is keeping secrets out of the repository entirely, using environment variables or a secret manager, and adding a scanning hook that rejects a commit containing credential-shaped strings before it is ever created.

Related Questions