If you accidentally committed a .env file to your Git repository, you cannot remove it directly through GitHub’s web interface. You must use Git commands to rewrite history.
GitHub officially recommends using git filter-repo instead of git filter-branch because it's faster and safer.
Check if git filter-repo is installed:
git --versionIf not installed, install it:
On macOS (Homebrew):
brew install git-filter-repoOn Linux (Ubuntu/Debian):
sudo apt install git-filter-repoIf you haven’t already cloned your repository:
git clone --mirror https://github.com/yourusername/yourrepo.git
cd yourrepoRun the following command to completely remove .env from Git history:
git filter-repo --path .env --invert-pathsgit push origin --force --allAfter removing the file from history, ensure Git ignores it:
echo ".env" >> .gitignore
git add .gitignore
git commit -m "Add .env to .gitignore"
git push origin mainIf the .env file was added in a recent commit and you don't want to rewrite the entire history:
-
Remove the file from the repository:
git rm --cached .env
-
Commit the change:
git commit -m "Remove .env file from repository" -
Force push the changes:
git push origin --force
- Force pushing (
--force) rewrites history, so team members must sync their local copies to avoid conflicts. - If the repository is public and someone already cloned it, the file might still exist in their copy.
- If credentials were inside
.env, assume they are compromised and rotate them immediately.