Deleting .env file back from Git

Sometimes , we accidentally pushed a file with some username , password or secret tokens etc. It has a variety security concerns for your project and this should be removed back from Git.

Git ignore

First thing you need to do is to add the file you don’t want to push to git at .gitignore file. Add it in .gitignore , commit and push it.

# Secret file

But this will not change any effects to .env as the file is already pushed before and .gitignore doesn’t untracked the already committed changes

Deleting the file

So we have to remove the specific file , .env in our case from the git remote repo entirely. We can use the following command.

git rm -r --cached .env

If we push the changes , the .env file will be remove from the remote repository

Git History

However, one more thing is left which is git histories. We can check the .env file contents also in git histories. So we need to remove the specific git history as well to hide the .env contents.

To remove the file altogether, we can use like following.

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch .env" HEAD

When you push this time, you have to use –force option.

git push --force

If we look at our history, we can still see the commits that include .env file but the content is empty.

That’s all for now.





tel. 06-6454-8833(平日 10:00~17:00)