Sometimes, we accidentally commit files that should have been ignored, like config/config.js
, .env
, or node_modules/
. Adding them to .gitignore
after committing doesn’t remove them from Git's history. Here’s how you fix it properly.
Step 1: Add the File to .gitignore
First, make sure the file is listed in .gitignore
.
# Ignore config file
config/config.js
Step 2: Remove the File from Git Tracking
Since Git is already tracking the file, we need to untrack it without deleting it from the local system.
Run this command:
git rm --cached config/config.js
✅ This removes it from Git without deleting it locally.
Step 3: Commit and Push the Change
Now, commit this change:
git commit -m "Removed config.js from repo"
git push origin main # Change 'main' if using a different branch
From now on, Git will ignore config/config.js
, and it won’t be included in future commits.
Bonus: Remove It from Git History (If Already Pushed)
If the file was already pushed and contains sensitive data, you need to rewrite Git history:
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch config/config.js' \
--prune-empty --tag-name-filter cat -- --all
Then force push the changes:
git push origin --force --all
⚠ Warning: This rewrites history, so be cautious if working in a shared repository!
Now your secret files are safe, and Git will ignore them in the future! 🚀
Top comments (0)