For developers, unintentionally uploading private data to a public repository can be catastrophic. Pushing the .env
file, which contains sensitive data including API keys, passwords, and other credentials, is one of the most frequent mistakes. Don't panic if you've unintentionally pushed a .env
file to a Git repository! To protect your private data, we'll go over how to safely delete a .env
file that was accidentally pushed in Git in this article.
First Things First: Save the .env
File to .gitignore
Place .env
in the .gitignore
file to prevent it from being pushed to the repository in the future. If you haven't already, create a .gitignore
file in the root directory of your project. Add .env
to the .gitignore
file to ensure that it is not included in the repository.
Remove the .env
File from the Git Repository
To remove the .env
file from the Git repository, run the following commands:
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch .env" HEAD
Force Push the Changes
git push --force
# or
git push origin <branch-name> --force
Voilà! The .env
file has been successfully removed from the Git repository. Remember to update your credentials and API keys to prevent unauthorized access to your application.