Since SFTP is secure than FTP, we always prefer the SFTP setup rather than FTP setup. (If you are new to SFTP, you can read about the key difference between FTP and SFTP. Others, read on.)
Restrictive SFTP User
Please note, the below process is applicable to Ubuntu, and I assume you have already created the site
Let’s assume the root directory of your site is /home/client_user. So when running the below commands, change /home/client_user to your site’s root directory.
Create a New User
Now, lets create a new user named ‘client_user’ and assign that user /home/client_user directory as a home directory. Fire up your terminal to connect to your server. Once you are connected, below command can be used to create a user. Make sure you replace client_user with the username you prefer and /home/client_user with the directory you want to assign to that user.
sudo useradd -d /home/client_user client_user
(Interested in reading about other options which can be passed to useradd? If yes, then you can read through these examples.)
Set a Password
Once the user is created, we need to set a password. To set a password for that user, execute the below command
sudo passwd client_user
We are ready with the new user now. Its time to make some changes in our SSH configuration.
Restrict Access
Open the /etc/ssh/sshd_config file and append the below given code. (Remember to replace client_user with username you have created)
subsystem sftp internal-sftp
Match User client_user
ChrootDirectory %h
AllowTCPForwarding no
X11 Forwarding no
ForceCommand internal-sftp
%h stands for home directory.
After doing the above changes, save the file and restart the SSH service. To restart SSH service, execute
sudo service ssh restart
Done! Now try logging into the system with the new user’s credentials, and check if everything is working correctly.
One last tip: For those of you who get a ‘fatal: bad ownership or modes for chroot directory’ error, do not worry. When this issue occurs, we need to make sure that the home directory of a user is owned by root and no one else can write into that directory. So change the owner of home directory using the following commands:
sudo chown root:root /home/client_user
sudo chmod 755 /home/client_user
After changing the permissions, try it again. If it still does not work for you, do leave your comments. I will be more than happy to help you