Skip to content

hash123shaikh/how-to-remove-sensitive-data-from-github

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

14 Commits
Β 
Β 

Repository files navigation

πŸ” How to Remove .env Files or Sensitive Data from GitHub

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.


🚫 Step 1: Prevent Future Mistakes Using .gitignore

Before pushing any project:

  1. Create a .gitignore file 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).
  2. Add these common sensitive patterns to the .gitignore file:
# .gitignore
.env
*.env
*.key
*.pem
*.crt

This tells Git to ignore these files β€” they won’t be tracked or pushed to GitHub.


🧹 Step 2: Remove Already Committed .env File

If you’ve already committed a sensitive file, follow these steps:

🧼 A. Remove It from the Current Commit

git rm --cached .env
git commit -m "Remove .env file from repository"
git push

This removes the file from Git tracking, but not from the history.


🧨 B. Remove It from Entire Git History (Using BFG or Filter-Repo)

Option 1: Using BFG Repo Cleaner (Easy)

  1. Download: https://rtyley.github.io/bfg-repo-cleaner
  2. Run:
bfg --delete-files .env

Then clean and push:

git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --force

Option 2: Using Git Filter-Repo (Advanced)

git filter-repo --path .env --invert-paths

This permanently deletes .env from your entire repo history.


🧠 Best Practices

  • βœ… Always use .gitignore before pushing

  • βœ… Use .env.example to share structure of .env without exposing secrets

  • ❌ Never share AWS keys, tokens, or credentials in code


πŸ“¦ Sample .env.example

# env file

AWS_ACCESS_KEY=your_key_here
AWS_SECRET_KEY=your_secret_here
DB_HOST=localhost

πŸ“š References


πŸ™Œ Feel Free to Clone & Share

Created by @hash123shaikh to help others avoid this common mistake.

About

A perfect guide on how to prevent and remove `.env` files or sensitive data from GitHUb repositries. Includes cleanup commands, best practics, and sample files for safe code sharing.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors