Have you pushed any secret keys or credentials lately into your git repository? Are they private repositories on any hosting services? How well can you trust if it’s a private repository? Leaks can happen and with that your secrets may be at risk. Here’s how you can remove the secret files such as .env.
Step 1
Install git-filter-repo by running:
sudo apt install git-filter-repo
Depending on the OS you are running on, you may have to change apt to brew (macOS) or dnf (Fedora).
Step 2
Navigate to your project folder and run:
git filter-repo --path .env --invert-paths
Step 3
Check if the history for the .env file is cleared:
git log --all --full-history -- .env
The output should return empty if it’s cleared else you would see messages with date time of the changes of .env
Step 4
Add a new commit to denote this change:
echo ".env" >> .gitignore
git rm --cached .env
git commit -m "Stop tracking .env file"
Step 5
If you already have a remote configured, you may have to re-add the URL:
git remote add origin <REPO URL>
Step 6
Force push to the remote repository as changes are made throughout the history:
git push --force
Conclusion
Removing sensitive files from your Git history isn’t just about fixing a mistake—it’s about building sustainable security practices into your development workflow. While private repositories offer a layer of protection, they shouldn’t be your only line of defense against human error, compromised credentials, or unexpected access changes. The techniques we’ve covered give you the power to rewrite history and eliminate exposed .env files, but the real lesson is prevention: implement .gitignore rules from the very first commit, use environment variable management tools, and consider secret scanning solutions that catch credentials before they’re pushed.