A .env file or API key in Git history – rotate first, then rewrite history

By Abheesht Tripathi · Published

Risk: .env, service account JSON, sk_live_..., sb_secret_... or a database URL committed to a repository, even if a later commit deleted it

Why deleting the file is not enough

A later commit that deletes .env removes it from the current files, not from history. Anyone with the repository can run git log -p and read it. Public repositories are scanned by bots continuously, so assume a secret pushed to a public repo was copied within minutes. Rewriting history helps for the future, but it can't un-copy anything: forks and clones keep the old commits. That is why rotation comes first.

Step 1: rotate every secret in the file, now

GitHub's own guide says the first step is to revoke or rotate the secret. Go provider by provider:

Update the new values in your hosting provider's environment settings and redeploy. Then check each provider's logs for use of the old key between the push and the rotation.

Step 2: find every commit that contains it

git log --all --full-history --oneline -- .env
git log --all -p -S 'sk_live_' --oneline      # search contents by a fragment of the secret

Step 3: stop tracking the file

echo ".env*" >> .gitignore
echo "!.env.example" >> .gitignore
git rm --cached .env
git commit -m "Stop tracking .env"

Step 4: rewrite history with git-filter-repo

Work on a fresh clone. GitHub's guide uses git-filter-repo (version 2.47 or later for the --sensitive-data-removal option):

git clone git@github.com:you/app.git app-clean && cd app-clean

# remove the file from every commit
git filter-repo --sensitive-data-removal --invert-paths --path .env

# or replace secret strings wherever they appear (one per line in a file outside the repo)
#   ../secrets.txt contains lines like:  sk_live_abc123==>REMOVED
git filter-repo --sensitive-data-removal --replace-text ../secrets.txt

git push --force --mirror origin

Pushes to refs/pull/* are rejected because GitHub treats them as read-only, so old pull requests can still show the secret. GitHub's guide says to contact GitHub Support with the repository and the first changed commits so they can remove cached views and affected pull request refs. Everyone with a clone must re-clone; an old clone pushed back brings the secret back.

Step 5: block the next one

How to verify

The old keys fail with an authentication error at each provider. git log --all -p -S '<fragment>' on a fresh clone finds nothing. A test commit containing a fake key in a recognised format is blocked by push protection.

Related guides

More in Auth, JWT and secrets · all guides