Mistakenly pushed .env file to remote repo?

When you start your web development journey, you would have been asked to learn git as a necessary skill to get into any position. And you might have learned almost daily usage git commands to push your code locally to remote repo (either would be Github, GitLab or any other platform ). While learning git, you have been warned about should not commit .env file to remote repo as it exposes your variables to public and that cause your variables would be misused by others.

I came across that situation when I was pushing my local code to Github repo, accidentally sending out env file to the remote repo along with other files. If you have ever gone through that phase and are confused about what to do then this blog is for you.

Steps to remove the .env or any other file from your git history :

  1. First of all, make sure you have a copy of the project before proceeding as it gonna rewrite the complete git history.

  2. Install the git filter-repo command into your system

     sudo apt-get install git-filter-repo (In linux based systems)
    
  3. Type this command in your project root terminal

     git filter-repo --path PATH_TO_YOUR_SENSITIVE_FILE --invert-paths
    

    (Make sure you replace your env file path to PATH_TO_YOUR_SENSITIVE_FILE )

  4. The above command will rewrite the history of your local code by deleting the file you wanted. Then run this command to push changes to your remote repo

      git push origin --force --all
    

    (This command will push the changes to remote forcibly)

  5. Tell your collaborators/team members to re-clone the project again as it has been outdated by rewriting the commit history.

    I would highly suggest you read git-filter-repo documentation for further help regarding this command use cases as it could help you in replacing the string or removing the complete folder also from your commit history