The short answer is, “yes”. You should use your .gitignore
file to ignore the .env
file.
Why Ignore .env
The .env
file is typically used for the configuration of your application, which often includes sensitive information like database credentials and API keys. Even if your Git repo is not public, it is a best practice to exclude this information from your repository (the idea being that sensitive configuration information should have higher security than source code).
How to Exclude .env
You can exclude your .env
file by adding the following line to your .gitignore
file.
.env
In my case, I like to exclude all files that start with a period with exceptions (e.g. .gitignore
is an exception).
Warning: If your .env
is already part of your Git repository, adding it to .gitignore
will not remove it. In this case, you’ll also need to tell Git to stop tracking .env
, which you can do with
git rm --cached .env
This will delete .env
from your repo, but leave it on your local machine (and now your .gitignore
will cause it to be ignored).
Damage Control
If your .env
was checked into your repo, you’ll want to change any credentials that appear in it. This isn’t a lot of fun however even though you are no longer tracking your .env
file, it is still part of your Git history and can be retrieved.
You can take steps to remove it from your Git repo entirely but this comes with a host of problems and still does not guarantee there is not a copy of the .env
file somewhere.
If sensitive information gets added to a Git repository, it should be changed.
Include .env.example
Because it is helpful to have a template for your .env
file, you’ll often see an .env.example
file. This file contains the same structure as your .env
file but all of the credentials and API keys have been removed. This helps speed up the process of setting up your project.
Leave a Reply