Accidentally pushed .env, passwords, or other credentials to GitHub? Donβt worry β this repo explains how to remove sensitive files from your Git history safely and properly β and prevent it from happening again.
Before pushing any project:
- Create a
.gitignorefile in the root folder of your project directory β the same location where your.py,.ipynb, or source code files are stored (if not already present). - Add these common sensitive patterns to the
.gitignorefile:
# .gitignore
.env
*.env
*.key
*.pem
*.crtThis tells Git to ignore these files β they wonβt be tracked or pushed to GitHub.
If youβve already committed a sensitive file, follow these steps:
git rm --cached .env
git commit -m "Remove .env file from repository"
git pushThis removes the file from Git tracking, but not from the history.
Option 1: Using BFG Repo Cleaner (Easy)
- Download: https://rtyley.github.io/bfg-repo-cleaner
- Run:
bfg --delete-files .envThen clean and push:
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --forceOption 2: Using Git Filter-Repo (Advanced)
git filter-repo --path .env --invert-pathsThis permanently deletes .env from your entire repo history.
-
β Always use
.gitignorebefore pushing -
β Use
.env.exampleto share structure of.envwithout exposing secrets -
β Never share AWS keys, tokens, or credentials in code
# env file
AWS_ACCESS_KEY=your_key_here
AWS_SECRET_KEY=your_secret_here
DB_HOST=localhost
Created by @hash123shaikh to help others avoid this common mistake.