DEV Community

DOUGLAS EMMANUEL🇳🇬
DOUGLAS EMMANUEL🇳🇬

Posted on

How to Remove .env Files from Your Git Commit History (And Why You Should)

Have you ever pushed a .env file to your Git repository, only to realize it contains sensitive data like API keys, database credentials, or other private configuration values? It’s a stressful moment—especially when deleting the file from your working directory doesn’t actually remove it from your commit history. Anyone who can access your repo can still view those secrets in earlier commits.
But don’t worry. In this guide, I’ll show you how to permanently remove .env from your Git history using a modern, safe approach. By the end, your project will be secure and your credentials fully protected.

STEP 1
Install git-filter dependency by open your terminal and tun this command
$ PACKAGE_TOOL install git-filter-repo
for macos is brew , windows could be npm , pip etc.

Step 2
Navigate to your project folder and run this command in it
git filter-repo --path .env --invert-paths

Step 3
Double Check if the .env is gone by running this command
git log --all --full-history -- .env

Step 4
Add a .env file containing your environment Keys , in your project folder run this command.

echo ".env" >> .gitignore
git rm --cached .env
git commit -m "Stop tracking .env file"

Step 5
After going through all the steps do a force push to clean the git history by running this command.
git push —force

Step 6
verify if your changes were made by running this command git log --stat | grep .env

Conclusion
Accidentally committing a .env file happens to even the most experienced developers — but now you know exactly how to clean it up the right way. With git filter-repo, you can wipe sensitive files from your entire commit history using one simple command, ensuring your project stays secure and your credentials remain protected.

Thanks for Reading 😊.

Top comments (0)