How to remove a file from your git history.

You have done it! There is a .env file with your secrets in your git history... But this is not the end of everything!

You have to type the following command and replace __file_path__ with the file path you wish to remove.

git filter-branch --force --index-filter "git rm --cached --ignore-unmatch __file_path__" --prune-empty --tag-name-filter cat -- --all

This is a quite brutal and drastic way of tackling this issue. You just rewrote the entire history of all the branches containing your file since the moment you pushed it for the first time. Your git won‘t like it, you will see warnings, and on a large codebase, it may take a few minutes. But doing so, you removed the file from all the snapshots in your beautiful directed acyclic graph and don’t have to worry about it anymore.

Of course, you must now force push to your remote origin; which needs to completely rewrite itself. And everyone in your team needs to pull and rebase.

I have been told that there is a way to remove specific lines and to be more surgical. But with the bazooka, you make sure that you killed the fly. You can add back your deleted files in a later commit. But not your.env file! This one should be directly added to your .gitignore!

To avoid such misfortune in the future, you should start using a Secret as a Service like knox.

Try Knox for free

If you want to know about the horror story behind Knox, I wrote a piece about it here.