I was learning web development, and while making a project I forgot to add .env
file in .gitignore
, and pushed it to a public repository in GitHub.
You might be facing a similar problem or have a file with sensitive data pushed to the remote repository. If yes then here's the solution.
Add the file to your .gitignore
# gitignore
.env
Removing a file from Git
In your terminal type the following command.
git rm -r --cached .env
This command removes the .env
file or directory from the staging area of git, ensuring that it will not be included in the next commit. However, the actual file will not be deleted from the local directory.
Push the changes, you will see that the file is gone in GitHub.
However, this didn't completely solve our issue. If we look at our Git history, we can still find the file and expose the secrets!
Completely remove a file from Git history
To remove the file altogether, we can use the following command.
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch .env" HEAD
You will get some warnings about this messing up your history as this goes through your whole history and 100% removes its occurrence.
To push this, you have to run the following command.
git push --force
If we look at our history, we can still see the commits that include this .env
file, but the content is empty.
And you will be good to go!
Similarly, other files' history can also be deleted by changing ".env" to the location of the file.
Do like the post if this helped ๐.