First, you should ensure that your username is included in www-data group. If not, you can add your username as www-data group
sudo adduser $USER www-data
After that, you should change the ownership of /var/www to your username
sudo chown $USER:www-data -R /var/www
Next step, you should change permission to 755 (rwxr-xr-x), not recommend changing permission to 777 for security reason
sudo chmod u=rwX,g=srX,o=rX -R /var/www
Run the following command when you get the error: error: cannot open .git/FETCH_HEAD: Permission denied
sudo chmod g+w .git -R
For Wordpress or Joomla site, you may need to run the follwing command to fix the permission issues
sudo chown -R www-data:www-data /var/www/CMS_DIRECTORY
For directories only do this.
find . -type d -exec chmod 755 {} \;
For files only do this.
find . -type f -exec chmod 644 {} \;