Update: Recently I've converted this answer into a useful script and extensively start using it with VSCode and its SSH abilities. The script is now available at GitHub: bindfs-to-home-bash.
Here I'm assuming you are able to ssh/sftp to your user's home directory successfully and you want to edit (with your user) files and folders under
/var/www that are owned by
www-data:www-data (without changing their ownership).
Here I'm assuming also the topic How to avoid using sudo when working in /var/www? doesn't cover you needs. For example you don't want to change the permissions under
I think the most easiest and clear way to solve this task is to mount
/var/www (or certain directory inside) into your user's home directory and change the owner to your user and :group. This could be achieved by the tool
sudo apt update && sudo apt install bindfs
Here we will mount the entire directory
/var/www in a directory called also
www/ and located in your user's home directory.
sudo bindfs -u $(id -u) -g $(id -g) --create-for-user=www-data --create-for-group=www-data /var/www "$HOME/www"
The command substitutions
$(id -u) and
$(id -g) will return the UID and GID of the current user.
If you want to execute the above command for another user use
$(id -u <user>) and
$(id -g <user>). Where
<user> is an actual username.
For more details about the arguments used with
bindfs read its manual page -
If you want to un-mount
$HOME/www) use the command:
sudo fusermount -u ~/www
~/www automatically during the system startup add the following line into the bottom of
bindfs#/var/www /home/<user>/www fuse force-user=<uid>,force-group=<gid>,create-for-user=www-data,create-for-group=www-data 0 0
Note: you should replace
<user> with the actual username; also should replace
<gid> with the actual UID and GID of the
<user>, you can find them by the commands:
id -u <user> and
id -u <user>.
To see the result reboot the system or execute:
sudo mount -a # maybe you should execute `sudo fusermount -u ~/www` first
Here is animated demo how this works:
The only limitation of this approach that I found is when you change the ownership of the bind directory this will change the ownership also for the source directory. For example the next command is not a good idea:
chown -R $(id -u):$(id -g) $HOME/www
Maybe there is a suitable option for the
bindfs command that will prevent this to happen, but I can't tell that at the moment.