Set Up Apache Virtual Hosts On Debian
Apache server uses virtual hosts to run multiple domains on a single IP address.
It is really useful if you are running VPS and you want a few sites on it.
You can set up unlimited virtual hosts on apache.
In this tutorial I will show you how to set up apache virtual hosts on Debian Linux but you can do that on every other operating system.
Requirements
Things you’ll need for this tutorial:
- Apache web server (see LAMP Installation for apache installation)
- Domain name
If you don’t have a domain name, you can set one for free at No-IP.
(see Make a subdomain with No-IP)
1. Creating directory for new website
We need to create directory for our new website.
Go to apache www directory:
cd /var/www
And make a new directory for your website:
sudo mkdir site.com
Note: Name of the directory is not important but it is easier to name it after domain name
2. Setting permissions
We need to change some permissions.
Set site.com directory permissions to your user:
sudo chown -R $USER:$USER /var/www/site.com
Note: This will give your user rights to make changes to site.com directory
3. Creating files in site directory
We will make an index.html file which is going to show if we successfully created virtual host.
Go to newly created directory:
cd site.com
And create index file which will be used for testing later
nano index.html
Insert following lines:
<html> <head> <title>site.com</title> </head> <body> <h2>site.com virtual host is created!</h2> </body> </html>
Save and exit file.
4. Configuring Apache server
Next thing to do is to configure apache server.
We need to add our website to apache so it can be accessed over a domain name.
Go to:
cd /etc/apache2/sites-available
Make a copy of default apache configuration file
cp default site.com
Note: site.com is the name of our new website configuration file
Edit newly created configuration file:
sudo nano site.com
Make sure you have following lines under <VirtualHost *:80>
ServerAdmin admin@site.com ServerName site.com ServerAlias www.site.com
Next thing you need to edit is DocumentRoot line.
We need to change it to site.com directory, so you need to type:
DocumentRoot /var/www/site.com
Editing configuration files is now finished.
5. Finishing up
We need to tell apache that new site is now available and ready for use:
sudo a2ensite site.com
Our website is now added and next thing to do is to restart apache server to apply changes:
sudo service apache2 restart
You have now configured your apache virtual host for your new website.
Now open your Internet browser and type your domain name to access your newly created website on your server.
If everything went fine, you should see the following line in your browser:
site.com virtual host is created!
It is the line we created earlier in index.html file (Section 3.).
You can now add new virtual hosts repeating the process and make sure to enter appropriate Document Root.