.gitignore Generator · Tutorial
How to stop committing .env files and secrets to git
6 min readbeginnerUpdated
Your project keeps API keys in a .env file and you want to be sure it never reaches GitHub. You will add the right rules, keep a safe .env.example for teammates, and fix the case where .env was already committed.
What you need
- The .gitignore Generator
- A git repository on your computer
Steps
Include the secrets rules
Load the example and check that Secrets (.env files) is ticked. It adds
.envand.env.*to ignore every environment file, then!.env.exampleto keep the example..env .env.* !.env.exampleTest the rules
In Is this path ignored? type
.env.local: it is ignored by.env.*. Now type.env.example: it is not ignored, because the!line comes later and the last match wins.Save the file
Download the result and save it as
.gitignorein the repository root. Rungit status: the .env file no longer appears as a new file.Fix an already-tracked .env
If .env was committed before, git keeps tracking it. Remove it from the index without deleting it from disk, then commit.
git rm --cached .env git commit -m "Stop tracking .env"Rotate the exposed secrets
A committed secret stays in the repository history even after this. If the repository was ever pushed, create new keys and revoke the old ones.
Try it yourself
Opens the .gitignore Generator with this tutorial's sample loaded.
Common mistakes
- Putting the rule below a broader !
- The last matching line wins. A later line such as
!*.localwould bring.env.localback. Keep the secrets rules after general rules. - Expecting .gitignore to remove history
- Ignoring a file only affects the future. Rotating the secret is the only safe fix once it has been pushed.
Next steps
Go back to the .gitignore Generator, or keep going with one of these:
FAQ
Should I commit .env.example?
Yes. List every variable your app needs with dummy values, so teammates know what to fill in.