Pushed .env File to GitHub

Pushed .env File to GitHub

Did you push your .env files to GitHub?

Did you simply delete that file?

Do you think you’re safe now?

YOU’RE NOT!

In this article, you’ll learn how to completely remove every trace of Environment Files from your repository.

So, you may have accidentally pushed your .env files to Github. The most common reason for this is that you forgot to add it to your gitignore file.

The first thing you should do is add your .env to your gitignore file. Just add this to your gitignore.

.env

That should fix things, right?

Let's try pushing your code to the repository now.

You’ll notice the .env file is still available. This is because the .gitignore file doesn't untrack already committed changes.

How to fix this?

To remove the .env file from your GitHub repository, run the following command in your terminal.

git rm -r --cached .env

Once you run this, you will notice the .env has been removed from the repository.

But that is not the end of your problems. If someone looks at your Git history, he/she can still find the file and expose the secrets!

How to remove the Git History?

To remove every trace of the .env file ever being exposed, run the following command in your terminal.

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

Once this command is run, push your code to GitHub again with the following command.

git push --force

If you look at your Git history, you will still find the .env file. But now the contents of the file are empty.

If you learned something new or if this helped you save your secret keys, do follow me!