How to apply .gitignore to an existing Git repository

Ralph J. Smit Laravel Software Engineer

Git is an awesome tool to track the version history of your files and to collaborate on software development. Almost every project you create has a .gitignore file, to specify which files in the directory should not be tracked by Git. But sometimes you want to change or update your .gitignore in order to remove a file from your repo. Unfortunately, those changes are not reflected immediately by Git: you have to apply the .gitignore file again.

In this article I'll show you how to apply the .gitignore file again on your project – and make sure that every change is applied.

Remove all files from the Git index

Git captures the state of your files in a so-called index. Every file that is excluded with .gitignore, is not added to the index. But what about files that are already in the index? To apply the .gitignore to them to, you'll need to empty your index first, and fill it then again.

Emptying your index can be done by running the following command. It's recommended to start with a clean working directory, so commit your work or stash your changes first.

git rm -r --cached .

You'll see a big list with output like this:

rm 'folder/file.php'
rm 'folder/file2.php'

Now your index is empty! If you'd do a commit now, Git would think that you removed every file in your working directory. In fact, your working directory is still completely intact. So don't worry about losing files.

Advanced: how to remove only **one file** the index

Removing one file from the Git index is also very simple: just replace the dot ('.') in the command with the correct filepath. E.g. "git rm -r --cached folder/file2.php".

Add all files back again

Now you'll need to add every file back again. You can do this with the following simple command:

git add .

This makes sure that every file is added back to the index again, except for the files in the changed .gitignore. This is exactly what we want!

Commit our changes after applying .gitignore again

The last step is not strictly necessary – but I'd still recommend it. That step is committing the state of the directory. The changes in the commit are the files you removed from the git repository history.


As you've seen, it's very easy to apply the .gitignore file again to an existing Git repository. It takes less than a minute and can be used on almost any occasion!

Published by Ralph J. Smit on in Git . Last updated on 10 March 2022 .