Create a user and restrict him to his home directory on Ubuntu 14.04

When you want to give someone an access to your website or server, you don’t want to give him your personal login credentials. The best way is to create a new user and restrict this new user to his own directory.

It is also useful if you want to host the website of a friend on your server, but you don’t want your friend to mess up with all your personal files. The easy solution : create him an account.

Open a terminal, login to your server via ssh and follow these steps:

# create a new user (john for this example)
# just enter a password when asked, confirm it, and the other steps are optionals
sudo adduser john
# give root user the ownership of john's home directory
sudo chown root:root /home/john
# edit the ssh configuration file
sudo vim /etc/ssh/sshd_config
# restart ssh
sudo service ssh restart
# add these lines
Match user john
# Change the root of john user to his home directory
ChrootDirectory /home/john
AllowTcpForwarding no
ForceCommand internal-sftp
# create a public web folder for john
sudo mkdir /home/john/public_html
# give john the ownership of this folder
sudo chown -R john:john /home/john/public_html
# edit the apache configuration file
sudo vim /etc/apache2/apache2.conf
# add these lines to allow the webserver to access
# john public web directory
<Directory /home/john/public_html/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
# create a virtual host for john's website
sudo vim /etc/apache2/sites-available/johnwebsite.tld.conf
# add these lines to this file
<VirtualHost *:80>
ServerAdmin your@email.tld
ServerName johnwebsite.tld
ServerAlias www.johnwebsite.tld
DocumentRoot /home/john/public_html/johnwebsite.tld
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory /home/john/public_html/johnwebsite.tld>
Options -Indexes
AllowOverride All
</Directory>
</VirtualHost>
# activate the new virtual host
sudo a2ensite johnwebsite.tld.conf
# rerstart the webserver to validate the changes
sudo service apache2 restart
# create the folder for johnwebsite.tld website
sudo mkdir /home/john/public_html/johnwebsite.tld
# give john ownership of this folder
sudo chown -R john:john /home/john/public_html/johnwebsite.tld

Now you can upload the new website via sftp and give the user login credential to your friend.

Leave a comment