Occasionally a developer might commit some sensitive information, such as passwords, in a Git repository. Although you can easily remove the file in question from the repo, Git will retain the commit history for that particular file. Fortunately, in Git there is an easy way to remove files from Git history.
Let’s assume that the file in question is config.php. To purge the file from your repo you would run this Git command:
$ git filter-branch --index-filter 'git rm --cached --ignore-unmatch config.php' --prune-empty --tag-name-filter cat -- --all
This command will run the entire history of every branch and tag, changing any commit that involved the file config.php, and any commits afterwards. Now that you’ve removed the file from Git history, it would be wise to add it to .gitignore file to prent it from getting checked in again.
Note that this will overwrite your existing tags and branches. Now is a good time to make sure your local repo is in a good state before you force-push your changes to overwrite the remote repo:
$ git push origin master --force
You will have to repeat this for every affected branch and tag.
--all and --tags
might make that easier.
Final step to remove files from Git history is to purge the files from your local cache:
$ rm -rf .git/refs/original/ $ git reflog expire --expire=now --all $ git gc --prune=now $ git gc --aggressive --prune=now
That’s it. For more information on how to remove files from Git history, refer to this article on GitHub.