Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save kanchokanchev/c7af12184a344d43cfcefcc72e9ba6c4 to your computer and use it in GitHub Desktop.

Select an option

Save kanchokanchev/c7af12184a344d43cfcefcc72e9ba6c4 to your computer and use it in GitHub Desktop.
Git Repo - Permanently Remove A File From A Git History #GIT #GIT_HISTORY

How to Permanently Remove a .env File from GitHub History

If you accidentally committed a .env file to your Git repository, you cannot remove it directly through GitHub’s web interface. You must use Git commands to rewrite history.

Step 1: Remove the .env File from All Commits Using git filter-repo (Recommended)

GitHub officially recommends using git filter-repo instead of git filter-branch because it's faster and safer.

1. Install git filter-repo (if not installed)

Check if git filter-repo is installed:

git --version

If not installed, install it:

On macOS (Homebrew):

brew install git-filter-repo

On Linux (Ubuntu/Debian):

sudo apt install git-filter-repo

2. Clone Your Repository

If you haven’t already cloned your repository:

git clone --mirror https://github.com/yourusername/yourrepo.git
cd yourrepo

3. Remove the .env File from All Commits

Run the following command to completely remove .env from Git history:

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

4. Force Push the Cleaned History to GitHub

git push origin --force --all

Step 2: Add .env to .gitignore (Prevent Future Issues)

After removing the file from history, ensure Git ignores it:

echo ".env" >> .gitignore
git add .gitignore
git commit -m "Add .env to .gitignore"
git push origin main

Alternative: Manual Removal Using git rebase (Recent Commits Only)

If the .env file was added in a recent commit and you don't want to rewrite the entire history:

  1. Remove the file from the repository:

    git rm --cached .env
  2. Commit the change:

    git commit -m "Remove .env file from repository"
  3. Force push the changes:

    git push origin --force

Important Notes

  • Force pushing (--force) rewrites history, so team members must sync their local copies to avoid conflicts.
  • If the repository is public and someone already cloned it, the file might still exist in their copy.
  • If credentials were inside .env, assume they are compromised and rotate them immediately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment