Adding a file to .gitignore does nothing for files git already tracks. To make git forget one, you have to remove it from the index.
git rm --cached .env
echo ".env" >> .gitignore
git commit -m "Stop tracking .env"
--cached removes the file from the index only. Your working copy stays exactly where it is, and git status shows it as deleted for the next commit plus, until you ignore it, as untracked. For a folder, I’d add -r: git rm -r --cached build/.
After the commit, git stops looking at the file and the ignore rule finally does its job.
Two warnings. First, the file is removed from the repository, not from history. If it contained a password, it’s still in every older commit, so change the password. Second, for everyone else this is a normal deletion: when a teammate pulls your commit, git deletes the file from their working tree. For a local config file that everyone needs, tell people before you push, or give them a .env.example to copy from.
Further reading: git-rm documentation