/ GitHub

How to remove sensitive file from Github Repository

Creator Image
Bashar Alshaibani
24 Oct 2024 -
6 min Reading time

To use git filter-branch to remove a sensitive file (such as an API key) from the Git history, follow these steps carefully:

1. Backup Your Repository:

Before proceeding, make sure to back up your repository, as git filter-branch rewrites the Git history. It’s a good practice to make a copy in case anything goes wrong.

git clone --mirror https://github.com/yourusername/your-repo.git backup-repo.git

2. Remove the Sensitive File Using git filter-branch:

Run the following command to remove the sensitive file from all previous commits:

git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch path/to/your/apikeyfile' \
--prune-empty --tag-name-filter cat -- --all

Replace path/to/your/apikeyfile with the actual path to the file that you want to remove.

This command does the following:

  • --force: Forces the operation.
  • --index-filter: Filters the repository’s index (staging area) by removing the file.
  • --prune-empty: Removes any empty commits left over after the file has been deleted.
  • --tag-name-filter cat: Updates any tags to point to the rewritten commits.
  • -- --all: Runs the operation on all branches and tags.

3. Clean Up the Repository:

After running git filter-branch, you need to clean up and optimize the repository:

rm -rf .git/refs/original/  # Remove backup refs created by git filter-branch
git reflog expire --expire=now --all  # Expire all reflog entries
git gc --prune=now --aggressive  # Garbage collect to free up space

4. Add the File to .gitignore:

To ensure the sensitive file is not committed again, add it to .gitignore.

echo "path/to/your/apikeyfile" >> .gitignore
git add .gitignore
git commit -m "Add API key file to .gitignore"

5. Force Push the Changes to GitHub:

Since the history has been rewritten, you’ll need to force push the changes to GitHub.

git push origin --force --all
git push origin --force --tags

This will rewrite the repository history on GitHub and remove the file from all previous commits.

6. Notify Collaborators:

If this repository has multiple contributors, you should notify them, as the history rewrite will require them to perform a fresh clone of the repository:

git clone https://github.com/yourusername/your-repo.git

7. Rotate Your API Keys:

Since the API key was exposed, make sure to regenerate the API key from the service provider and update it in your project (privately, not in Git).

This process will effectively remove the API key from the Git history and ensure that it is not committed again in the future.