How to remove a leaked .env file from GitHub permanently...

Kodebae - Aug 31 - - Dev Community

OOoooppss...

Ok we don't have time to waste, you did the unthinkable, it was a rookie move, but we need to fix it asap! I'll skip any further banter and cut straight to the case. Here's how were gonna do it...


Quick Summary:

  • Remove .env and commit the removal.
  • Use filter-branch to delete the file from history.
  • Force push the changes.
  • Clean up the local repository.

1. Remove the .env File and Commit

  • First, remove the .env file from your repository and commit the changes:
bash
Copy code
git rm --cached .env
echo ".env" >> .gitignore
git add .gitignore
git commit -m "Remove .env file and add to .gitignore"
Enter fullscreen mode Exit fullscreen mode

2. Remove the .env File from History with filter-branch

  • Use Git’s filter-branch to remove the .env file from the entire history:
bash
Copy code
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch .env' --prune-empty --tag-name-filter cat -- --all
Enter fullscreen mode Exit fullscreen mode

3. Force Push the Changes

  • After running the filter-branch, you'll need to force push the changes to the remote repository:
bash
Copy code
git push --force --all
git push --force --tags
Enter fullscreen mode Exit fullscreen mode

4. Clean Up Local Repository

  • Finally, clean up your local repository to remove the old references:
bash
Copy code
rm -rf .git/refs/original/
git reflog expire --expire=now --all
git gc --prune=now --aggressive
Enter fullscreen mode Exit fullscreen mode

5. Revoke Any Leaked Credentials

  • As with any method, if your .env file contained sensitive information, revoke and regenerate those credentials immediately.


😅 You did it! Hopefully nobody saw that. Pat yourself on the back and please please please don't skip step 5. You need to revoke access and regenerate new credentials to insure that you don't get hacked. You've been warned...

Ok that's it, bye!

Credits:

Author: 👩🏽‍💻 Kodebae
Buy me a ☕️: (https://www.buymeacoffee.com/karmendurbin)
Website: (https://kodebae.github.io/kodebae-app/)
X: (https://twitter.com/karmen_durbin)

. . . . . . . . . .
Terabox Video Player