How To Set Up Apache Virtual Hosts on Ubuntu 14.04 LTS
How To Set Up Apache Virtual Hosts on Ubuntu 14.04 LTS
We hope you find this tutorial helpful. In addition to guides like this one, we provide simple cloud infrastructure for developers. Learn more →

How To Set Up Apache Virtual Hosts on Ubuntu 14.04 LTS

PostedApril 22, 2014 2.5m views Apache Ubuntu

Introduction

The Apache web server is the most popular way of serving web content on the internet. It accounts for more than half of all active websites on the internet and is extremely powerful and flexible.

Apache breaks its functionality and components into individual units that can be customized and configured independently. The basic unit that describes an individual site or domain is called a virtual host.

These designations allow the administrator to use one server to host multiple domains or sites off of a single interface or IP by using a matching mechanism. This is relevant to anyone looking to host more than one site off of a single VPS.

Each domain that is configured will direct the visitor to a specific directory holding that site's information, never indicating that the same server is also responsible for other sites. This scheme is expandable without any software limit as long as your server can handle the load.

In this guide, we will walk you through how to set up Apache virtual hosts on an Ubuntu 14.04 VPS. During this process, you'll learn how to serve different content to different visitors depending on which domains they are requesting.

Prerequisites

Before you begin this tutorial, you should create a non-root user as described in steps 1-4 here.

You will also need to have Apache installed in order to work through these steps. If you haven't already done so, you can get Apache installed on your server through apt-get:

sudo apt-get update
sudo apt-get install apache2

After these steps are complete, we can get started.

For the purposes of this guide, my configuration will make a virtual host for example.com and another for test.com. These will be referenced throughout the guide, but you should substitute your own domains or values while following along.

To learn how to set up your domain names with DigitalOcean, follow this link. If you do not have domains available to play with, you can use dummy values.

We will show how to edit your local hosts file later on to test the configuration if you are using dummy values. This will allow you to test your configuration from your home computer, even though your content won't be available through the domain name to other visitors.

Step One — Create the Directory Structure

The first step that we are going to take is to make a directory structure that will hold the site data that we will be serving to visitors.

Our document root (the top-level directory that Apache looks at to find content to serve) will be set to individual directories under the /var/www directory. We will create a directory here for both of the virtual hosts we plan on making.

Within each of these directories, we will create a public_html folder that will hold our actual files. This gives us some flexibility in our hosting.

For instance, for our sites, we're going to make our directories like this:

sudo mkdir -p /var/www/example.com/public_html
sudo mkdir -p /var/www/test.com/public_html

The portions in red represent the domain names that we are wanting to serve from our VPS.

Step Two — Grant Permissions

Now we have the directory structure for our files, but they are owned by our root user. If we want our regular user to be able to modify files in our web directories, we can change the ownership by doing this:

sudo chown -R $USER:$USER /var/www/example.com/public_html
sudo chown -R $USER:$USER /var/www/test.com/public_html

The $USER variable will take the value of the user you are currently logged in as when you press "ENTER". By doing this, our regular user now owns the public_html subdirectories where we will be storing our content.

We should also modify our permissions a little bit to ensure that read access is permitted to the general web directory and all of the files and folders it contains so that pages can be served correctly:

sudo chmod -R 755 /var/www

Your web server should now have the permissions it needs to serve content, and your user should be able to create content within the necessary folders.

Step Three — Create Demo Pages for Each Virtual Host

We have our directory structure in place. Let's create some content to serve.

We're just going for a demonstration, so our pages will be very simple. We're just going to make an index.html page for each site.

Let's start with example.com. We can open up an index.html file in our editor by typing:

nano /var/www/example.com/public_html/index.html

In this file, create a simple HTML document that indicates the site it is connected to. My file looks like this:

<html>
  <head>
    <title>Welcome to Example.com!</title>
  </head>
  <body>
    <h1>Success!  The example.com virtual host is working!</h1>
  </body>
</html>

Save and close the file when you are finished.

We can copy this file to use as the basis for our second site by typing:

cp /var/www/example.com/public_html/index.html /var/www/test.com/public_html/index.html

We can then open the file and modify the relevant pieces of information:

nano /var/www/test.com/public_html/index.html
<html>
  <head>
    <title>Welcome to Test.com!</title>
  </head>
  <body>
    <h1>Success!  The test.com virtual host is working!</h1>
  </body>
</html>

Save and close this file as well. You now have the pages necessary to test the virtual host configuration.

Step Four — Create New Virtual Host Files

Virtual host files are the files that specify the actual configuration of our virtual hosts and dictate how the Apache web server will respond to various domain requests.

Apache comes with a default virtual host file called 000-default.conf that we can use as a jumping off point. We are going to copy it over to create a virtual host file for each of our domains.

We will start with one domain, configure it, copy it for our second domain, and then make the few further adjustments needed. The default Ubuntu configuration requires that each virtual host file end in .conf.

Create the First Virtual Host File

Start by copying the file for the first domain:

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf

Open the new file in your editor with root privileges:

sudo nano /etc/apache2/sites-available/example.com.conf

The file will look something like this (I've removed the comments here to make the file more approachable):

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

As you can see, there's not much here. We will customize the items here for our first domain and add some additional directives. This virtual host section matches any requests that are made on port 80, the default HTTP port.

First, we need to change the ServerAdmin directive to an email that the site administrator can receive emails through.

ServerAdmin admin@example.com

After this, we need to add two directives. The first, called ServerName, establishes the base domain that should match for this virtual host definition. This will most likely be your domain. The second, called ServerAlias, defines further names that should match as if they were the base name. This is useful for matching hosts you defined, like www:

ServerName example.com
ServerAlias www.example.com

The only other thing we need to change for a basic virtual host file is the location of the document root for this domain. We already created the directory we need, so we just need to alter the DocumentRoot directive to reflect the directory we created:

DocumentRoot /var/www/example.com/public_html

In total, our virtualhost file should look like this:

<VirtualHost *:80>
    ServerAdmin admin@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Save and close the file.

Copy First Virtual Host and Customize for Second Domain

Now that we have our first virtual host file established, we can create our second one by copying that file and adjusting it as needed.

Start by copying it:

sudo cp /etc/apache2/sites-available/example.com.conf /etc/apache2/sites-available/test.com.conf

Open the new file with root privileges in your editor:

sudo nano /etc/apache2/sites-available/test.com.conf

You now need to modify all of the pieces of information to reference your second domain. When you are finished, it may look something like this:

<VirtualHost *:80>
    ServerAdmin admin@test.com
    ServerName test.com
    ServerAlias www.test.com
    DocumentRoot /var/www/test.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Save and close the file when you are finished.

Step Five — Enable the New Virtual Host Files

Now that we have created our virtual host files, we must enable them. Apache includes some tools that allow us to do this.

We can use the a2ensite tool to enable each of our sites like this:

sudo a2ensite example.com.conf
sudo a2ensite test.com.conf

When you are finished, you need to restart Apache to make these changes take effect:

sudo service apache2 restart

You will most likely receive a message saying something similar to:

 * Restarting web server apache2
 AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message

This is a harmless message that does not affect our site.

Step Six — Set Up Local Hosts File (Optional)

If you haven't been using actual domain names that you own to test this procedure and have been using some example domains instead, you can at least test the functionality of this process by temporarily modifying the hosts file on your local computer.

This will intercept any requests for the domains that you configured and point them to your VPS server, just as the DNS system would do if you were using registered domains. This will only work from your computer though, and is simply useful for testing purposes.

Make sure you are operating on your local computer for these steps and not your VPS server. You will need to know the computer's administrative password or otherwise be a member of the administrative group.

If you are on a Mac or Linux computer, edit your local file with administrative privileges by typing:

sudo nano /etc/hosts

If you are on a Windows machine, you can find instructions on altering your hosts file here.

The details that you need to add are the public IP address of your VPS server followed by the domain you want to use to reach that VPS.

For the domains that I used in this guide, assuming that my VPS IP address is 111.111.111.111, I could add the following lines to the bottom of my hosts file:

127.0.0.1   localhost
127.0.1.1   guest-desktop
111.111.111.111 example.com
111.111.111.111 test.com

This will direct any requests for example.com and test.com on our computer and send them to our server at 111.111.111.111. This is what we want if we are not actually the owners of these domains in order to test our virtual hosts.

Save and close the file.

Step Seven — Test your Results

Now that you have your virtual hosts configured, you can test your setup easily by going to the domains that you configured in your web browser:

http://example.com

You should see a page that looks like this:

Apache virt host example

Likewise, if you can visit your second page:

http://test.com

You will see the file you created for your second site:

Apache virt host test

If both of these sites work well, you've successfully configured two virtual hosts on the same server.

If you adjusted your home computer's hosts file, you may want to delete the lines you added now that you verified that your configuration works. This will prevent your hosts file from being filled with entries that are not actually necessary.

If you need to access this long term, consider purchasing a domain name for each site you need and setting it up to point to your VPS server.

Conclusion

If you followed along, you should now have a single server handling two separate domain names. You can expand this process by following the steps we outlined above to make additional virtual hosts.

There is no software limit on the number of domain names Apache can handle, so feel free to make as many as your server is capable of handling.

By Justin Ellingwood

265 Comments

  • Got stuck at the "Create the First Virtual Host File" step: my droplet has a file called "default" and "default-ssl" in sites-available, not "default.conf" as stated. And is the subsequent statement: "The default Ubuntu configuration requires that each virtual host file end in .conf." still correct?
  • @michaelleblanc1: It sounds like you are on a different Ubuntu release, perhaps 12.04. This tutorial is specifically talking about 14.04 where the file has been renamed from simply "default" to "000-default.conf" Assuming that you are on 12.04, you should be fine, but you might also want to take a look at this article: https://www.digitalocean.com/community/articles/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts
    by Etel Sverdlov
    This tutorial shows you how to set up a new directory, how to grant the correct permissions, how to add content to a new page, how to turn on virtual hosting, and how to, if needed, set up local hosts. Virtual Hosts are used to run more than one domain off of a single IP address and allows you to run multiple sites off of a single DigitalOcean droplet. This tutorial describes how to set up virtual hosts with Apache.
  • Thanks for this great tutorial. My primary virtual host (ie example.com) is alive and well. My droplet's ip address still points to /var/www/html though and provides the "Apache2 Ubuntu Default Page". I would like my ip to point to the new virtual host I created and hence to /var/www/test.com/public_html. How can I achieve this result? Thank you.
  • @Kerem: Do you still have the default configuration enabled? If so, edit the file "/etc/apache2/sites-enabled/000-default.conf" and change "DocumentRoot /var/www/html" to "DocumentRoot /var/www/test.com/public_html"
    • Hi, I've set up two virtual hosts like the article details and I'm having a similar issue to @kerem I want to be able to host two websites on the server, but in the /sites-enabled/000-default.conf there is only space for one (1) document root. How do I add in /var/www/doc/publichtml and /var/www/morgan/publichtml? I've done (and triple checked) the settings and files in this article. and I'm not sure what I'm missing.

    • @MorganJohnstone: Hello!

      To serve two websites with Apache, you'll have to create a virtual host for each. The main sections that deals with this is Steps 4 and 5.

      You'll want a virtual host file (a file that contains the configuration for a site between <VirtualHost *:80> and </VirtualHost> tags) for each of your sites. In one of them, you can have the document root pointed at /var/www/doc/public_html, and in the other, you can have the document root pointed at /var/www/morgan/public_html.

      The ServerName and ServerAlias directives in each of these virtual hosts will determine which content will be served by matching the values against the client's request.

      When you've finished creating a file for each of your sites, you need to enable them with the a2ensite command (this is covered in step 5). Afterwards, be sure to restart Apache.

      If you're still having issues after following these steps, post back with exactly what is happening. Hope this helps!

  • @Andrew SB, Thank you very much. This worked perfectly.
  • Thank you very much.. Your guide help me a lot. =)
  • Hi i had troubles pointing the domain to i'ts directory witch can be fixed by editing example.com.conf before: after: Now is working but i'm not sure that this is right solution.
  • Sorry "which" not "witch ".
  • I also had to specify Require all granted in the conf file as per http://httpd.apache.org/docs/2.4/upgrading.html
  • Posting comment filtered out the <> tags for lt tag directory /var/www/test.com/public_html/ gt tag Require all granted lt tag /directory gt tag in the conf file as per http://httpd.apache.org/docs/2.4/upgrading.html
  • It worked for me,by doing this tutorial i learned about config files, command line, and got a website! Thank-you, roosterscomputerrepair.with-linux.com
  • This works for me for 12.04 just by creating 000-default.conf instead of default default.conf. Now I am looking for how to incorporate secure (https) website as I have startssl.com certificate and key. Thanks for WONDERFUL work D.O.
  • i got stuck in sudo a2ensite example.com.conf my terminal said "Site example.com does not exist" i miss something, or this tutorial not working in ubuntu 14.10?
  • @mulyana2205: Does the file "/etc/apache2/sites-available/example.com.conf" actually exist? When you run "sudo a2ensite" make sure you use the name of the actual file you created.
  • You don't have permission to access / on this server.
  • @kasnca: Do you have an index file in your documentroot?
  • @kasnca: I was getting the same. Try adding: Require all granted It worked for me.
  • i copied the /etc/apache2/sites-available/000-default.conf over to /etc/apache2/sites-available/ididntsee.com.conf and edit it from there but am still getting the default apache 2 page instead of the index.html page I created two virtual host using two domain names I own and want to host on one droplet. The IP for one is still propagating but the first one is set and shows the default apache2 page.
  • Scratch the first comment. I started over from scratch, new server with new ip - directed both domain names to new IP, followed all directions including new non-root user and now all I am getting is 404 not found error on one site and "could not connect to isahappyperson.com" error on the other. I took each step slowly as to not make any mistakes so I have no clue what to do now. Does anyone know what is wrong? droplet server is on Ubuntu 14.04 LTS
  • update: I directed the domain names to the new IP in the DO dashboard but failed to change them where I registered the domain names. So, now one site works fine - is showing the custom index.html but the other site is showing the apache2 default index.html Any thoughts?
  • update: ididntsee.com is working www.ididntsee.com is working isahappyperson.com is NOT working www.isahappyperson.com is working both .com.conf files are the same except the domain name itself DocumentRoot /var/www/isahappyperson.com/public_html ServerName isahappyperson.com ServerAlias www.isahappyperson.com and... DocumentRoot /var/www/ididntsee.com/public_html ServerName ididntsee.com ServerAlias www.ididntsee.com So, why is one working and not the other?
  • Update: Glad to report that all is well and working fine. Had to run a2dissite 000-default then service apache2 restart All is good now :)
  • What if I need to host my server files outsite /var/www ? All of my projects are on my Dropbox folder and I simply cannot access them using the default virtualhost configuration on Ubuntu 14.04 + LAMP. I followed your instructions to the letter with no success. All I get is a 403 document with the message "You don't have permission to access / on this server." I tried other tutorials but none has solved my problem. Here's my virtual host configuration: < Virtualhost *:80 > DocumentRoot /home/brunowerneck/Dropbox/Projetos/websites/Site/web Servername site.servidor.home < Directory /home/brunowerneck/Dropbox/Projetos/websites/Site/web/ > AllowOverride All Require all granted < /Directory > < /Virtualhost > I have also tried to change folder ownership to root, to www-data and back to my user and chmod 755. None worked. Quotation marks on DocumentRoot and Directory directives make no difference. Any clues?
  • I did it! It turns out it was a permissions problem. By further reading Apache2 documentation, I noticed it said I had to give 755 permission on the entire path, not only on my DocumentRoot. So I did: cd /home/brunowerneck sudo chmod -R 755 Dropbox/ And voilà, everything works as they should! Finally!
  • Great Tutorial ... It is work.

  • but tis is onlt local how to make for internet ..who can help me to make it pls

  • @thedarkangel771: Are you installing this on a server that has port 80 open to the internet? If you're doing this on a local computer, you're most likely behind a router. You'd need to open the port in your router as well, but that's a little off topic for here.

  • Exactly what I needed, thank you Justin!! :)

  • Hi

    I used this tutorial and everything worked fine for me. Thanks for that.
    But I have opposite to usual question. Is it possible to get to this website by an internal ip without editing host file. I would like to avoid it, so everybody in local network could access webpage by ip.

    Btw. this website is working perfectly fine by typing URL in web browser from both internal and external network.

  • Great tutorial, thank you.

    How would I go about modifying my files to get my django project running? I tried pointing the document root to my django project, but all I get is a page with the files in my project i.e wsgi.py, urls.py etc. I want to use mod_python but I am not sure what to change.

  • @cebomakeleni: You need to usemod_wsgi. Check out the docs on the Django Project's site.

  • @bartosz.dega: You can add the IP as an alias of the Virtual host:

    ServerAlias www.domain.com 1.2.3.4
    
  • Running 14.04 lts 64 bit. Absolutely doesn't work for me. I have an existing virtual site as: lrwxrwxrwx 1 root root 10 Apr 23 08:54 bpslk -> /ddr/bpslk

    As you can see, it's a soft link to a directory in my "working-data" partition. This works fine. All of the files in /ddr/bpslk are are owned by me, and are set to 644, and all dirs are 755. There is no bpslk.conf file. Entering http://localhost/bpslk takes my browser to the index.html page located in /ddr/bpslk.

    So I added a soft link to /ddr/tipitaka and I get a 404 error.

    I have a dual-boot machine, so I rebooted in Linux Mint 15, entered the following commands in a terminal
    sudo cd /var/www
    sudo ln -s /ddr/tipitaka ./

    Then in my browser I typed localhost/tipitaka and it works! The tipitaka home page opens

    BTW I'm having the same trouble with Linux Mint 17 which is based on Ubuntu 14.04.

    I think there has been some update that has thrown a wrench into the works.

    Sure would like to resolve this, as now I have to do my web site development in Mint 15.

    -Harry

  • Hi there, I seem to miss something,
    I have multiple domains and they all go to toe same droplet, and all of them work properly except one but everything in the virtualhost is same as in the ones that work.

    Problem:
    getbootstraptheme.com works just fine but the www.getbootstraptheme.com returns error, like the domain would not be registered. Can it be that I messed something up in godaddy (the place where domain registered and routed to the droplet) ??
    i have duplich.com and www.duplich.com working just fine.
    both of the domains getbootstraptheme.com and duplich.com are registered at godaddy and routed to the same droplet via IP, but one is working fine and the other is broken...
    I can not figure out what is happening...
    Thanks for any advice

  • @jcausevi: www.getbootstraptheme.com loads fine for me, are you still experiencing this issue?

  • Hi there,

    I don't have a name for my server yet so how can i setup multiple virtualhosts in a way that i can access them using my ip?
    Example:
    http://1.2.3.4/firstapp goes to /home/user1/pythonapp/firstapp and
    http://1.2.3.4/secondapp goes to /home/user2/pythonapp/secondapp

    Is that possible?
    I tried this configuration but it didn't work:

    <VirtualHost *:80>
            ServerName server
            ServerAlias server 1.2.3.4/firstapp
            <Directory /home/user1/pythonapp/firstapp>
                    Order allow,deny
                    Allow from all
            </Directory>
    </VirtualHost>
    

    Thanks!

  • @faustovaz: You'll want to use Apache's Alias directive. It would look something like:

    <VirtualHost *:80>
        Alias /firstapp /home/user1/pythonapp/firstapp
        <Directory /home/user1/pythonapp/firstapp>
                Order allow,deny
                Allow from all
        </Directory>
    </VirtualHost>
    
  • This worked great for me - all 5 of my ".com" domains worked fine- HOWEVER my 6th domain was a ".biz" site and even though there is nothing out of the ordinary about it's configuration-- It defaults to the apache welcome page (/var/www/html) - I have removed the 000-default.conf file from both /etc/apache2/sites-available & /etc/apache2/sites-enabled - reloaded apache several times- no change in result for the ".biz" domain.

    • I had similar issue. The solution was to a2dissite (disable in other words) the 000-default.conf (don't delete it):

      1. go to /etc/apache2/sites-available/ folder.
      2. sudo a2dissite 000-default.conf
      3. sudo service apache2 restart

      Apparently 000-default.conf was causing errors and blocking my .conf files. Besides this fix, the tutorial is correct. And I didn't add any <directory> bits.

  • @Andrew SB, that worked perfectly.
    Thank you!

  • @will: Does its virtualhost file exist in /etc/apache2/sites-enabled? Make sure ServerName is set to yourdomain.biz and it's pointed to the correct IP address.

  • Stuck at ServerAdmin admin@amazonsurfandshop.com
    command not found
    Also tried admin@amazonsurfandshop.com
    command not found

  • @benea: These are not commands, they are the lines you need to edit in /etc/apache2/sites-available/example.com.conf using nano:

    sudo nano /etc/apache2/sites-available/example.com.conf
    
  • Thank you much Kamal. I got it. I think I'm getting dizzy. There are so much thing to do for just configuring the apache2.

  • I tested the results:

    For http://amazonsurfandshop.com -

    Apache2 Ubuntu Default Page: It works! With 2 pages detailed explanation.

    Not the lines typed in to the index.html - Success! The amazonsurfandshop.com virtual host is working!

    For http://test.com

    A real web page for test.com showed up.

    Is this a success results!

  • @benea: You need to replace test.com with your actual other domain name. :)

  • I don't have other domain. My only domain is amazonsurfandshop.com.

    Does the first result for http://amazonsurfandshop.com work though even it did not come out the message typed in the index.html "Success! The ......"

  • With respect to this Tutorial, is it absolutely necessary to use the public_html folder in setting up virtual hosts, or could you adjust it so that file uploads can go straight into the domain folder? In other words, I would rather set this up so that uploads go straight into

    http://yourdomain.com/

    rather than...

    http://yourdomain.com/public_html

    So, is this doable, and if so, what differences in setup from that tutorial are needed?

  • @info: This article configures Apache2 to serve the contents of /var/www/domain1.com/public_html for domain1.com, not /var/www/domain1.com. If you take a closer look at the DocumentRoot directive, you'll see that it points to the /var/www/domain1.com/public_html directory:

    DocumentRoot /var/www/example.com/public_html
    
  • Important if the virtual allways redirect to default html page : reload under sudo....
    sudo service apache reload
    Hope it will help ;)

  • Great tutorial!

    It was very easy and so clear, thanks a lot!

  • Thanks, every thing is fine

  • Just out of curiosity, what's the reasoning for setting world permission to octal 5? edit: I get that it has to do with the assumption that systems like Wordpress may involved components that assume need to write or have assumptions that might require world at execute, but what exactly then will that do? Is it not a severe security issue? (I will openly admit: I'm not sure what "execute" means in any precise manner in this context.)

  • I follow this tutorial but no hope, the apache2 won't serve any of html and images file but PHP file.
    There is no log in apache.log and error.log ...

    All i get is no response, no data received.
    But if i point to php file in the server, it work totally fine.

    Do you guys have any idea?

  • I followed every step of the tutorial and when i finally restart apache2 i get this error;

    • Restarting web server apache2 AH00112: Warning: DocumentRoot [/var/www/html] does not exist

    and when I type in the web address the website doesn't load. All it says is the requested URL wasn't found on this server.

  • This is a great tutorial. Do you have one that describes how to setup ampache with this? I'm trying to get ampache working external to the LAN but cannot access it via port 8080 even though I can access my apache server via web browser externally.

  • I followed the tutorial, but there is no change happen - I am keep getting the "Apache2 Ubuntu Default" page for the following domain recence.uk - Can someone please tell me where I go wrong.

    Aditional Info: I looked at the dir - there is a file exisits /recence.uk/public_html/index.html

  • All worked!! Thanks alot for the tutorial!

    Just 1 question, i have 2 sites, when 1 have a index.php and the other use a index.html it work. But when both have a index.php, my second site dont answer (like if there was no website installed).

    I need to configure anything else to make it work?

    Thanks!

  • Clear, concise instructions. Thank you.

  • Great guide! Really easy to follow! Thanks!

  • I wish to ask,, please tell me as based on the above settings and directory file arrangements, where I should put the website files?,, is it to be in; public_html folder with the index.html ?
    Thanks you in advance to all,,

  • i do that same as your articles but i got same page on both website .plz help me

  • Hi, I hope my question will not be out of the subject,, so if I may ask, the hosts settings on the above examples are what? external IPs (111.111.111.111 example.com) or local ? sorry to ask again but I have a problem to access the websites publicly,, it always redirect my websites to my Cisco Router log on page...http://sweetqcorner.com
    Thank you for any help,,

  • Can anyone tell me why my virtual hosts work when I enable in /etc/host adress 127.0.0.1 instead of 111.111.111.111 like author wrote it in this tutorial? Thank you.

  • Thanks for the great tutorial!

    a2ensite and other things are okay, i have checked everything as much as i can. The problem is when i try to go example.com or test.com it actually goes to the real website which is already on the internet.

    when i try to go file:///var/www/example.com/public_html/index.html it works except php command lines. (I am also incapable of php, but i will someday. Just copied a php command from the internet.)

    Little help will be appreciated, I am using Ubuntu 14.04.

    • Okay i found the solution.
      I just added
      127.0.0.2 example.com
      127.0.0.3 test.com
      to the hosts file with sudo nano /etc/hosts

      111.111.111.111 goes to nowhere, that was my problem. Thanks for the tutorial again.

  • thanks - clear and concise tutorial.

  • I got a strange problem.

    If I configure the address in my local hostfile it works just fine, but as soon as I remove it I get page not found. If I ping the address it looks up the correct ip but doesn't get any response.

    Any ideas?

  • Is there a way I can view the sites using the IP address?

    eg
    123.456.789.10/test.com
    123.456.789.10/example.com

    I've got it to work using Ubuntu 12.04 but not with 14.04

    • You can add a virtualhost for your IP address that points to /var/www which makes all of your domains accessible:

      <VirtualHost *:80>
          ServerAdmin admin@example.com
          ServerName 123.456.789.10
          DocumentRoot /var/www
          ErrorLog ${APACHE_LOG_DIR}/error.log
          CustomLog ${APACHE_LOG_DIR}/access.log combined
      </VirtualHost>
      
    • Perfect. Thanks!

  • Thank you for your tutorial. Apache configuration on Ubuntu was for a long time an enigma for me, now it is much clearer.

  • I'm getting stuck after the following:

    nano /var/www/mydomain.com/public_html/index.html
    

    when I create the html file. I enter the sample page,body in your example and try to save and get the following error. I've went back and ran the following command a couple of times and retried and it doesn't seem to help.

    sudo chown -R $USER:$USER /var/www/mydomain.com/public_html
    

    "[ Error writing /var/www/mydomain.com/public_html/index.html: Permission denied ]"

    Any ideas where I went wrong?

    Screenshots: Drive

    • What's the output of the following command?

      stat /var/www/mydomain.com/public_html /var/www/mydomain.com/public_html/index.html
      

      Also, what user are you connected as?

    • Hi @kamain7,

      I think I got it, not really sure what the issue was, maybe a timing issue. Afterwards I went and setup my private/public SSH key and logged in that way and it worked fine.

      Thanks for the follow-up.

  • Thanks Justin. This was very helpful.

  • This is not working for me at all. I keep getting the Ubuntu page instead of my index page. Everything is there. What am I missing?

    I've added my domain, the /var/www, everything I can think of and it just won't pull the index file.

  • how to make subdomain? just like test.example.com

  • Looks like your html tags are showing in this article. Maybe its my computer?

    And in the tutorial towards the first part what directory is it? It keeps changing from publichtml to public_html and then back and forth and I end up just having both...

  • Perfect! Thank you. I spent all day trying to get nginx to work. Got Apache to work first try thanks to this article.

  • My etc/hosts look like
    127.0.0.1 localhost
    127.0.0.1 ubuntu
    127.0.0.2 myhosting.com www.myhosting.com

    Then I you that we have to add the public IP address of my VPS, I assumed that my VPS IP address is 192.168.30.100 so it will look like this:

    127.0.0.1 localhost
    127.0.0.1 ubuntu
    127.0.0.2 myhosting.com www.myhosting.com
    192.168.30.100 myhosting.com

    I save it and in my browser i input myhosting.com and it does not display the page Success! The myhosting virtual host is working!

    Can you tell me why or where is the mistake? I try removing the assuming ip and even that it does not work....

  • This did not work for me, my page doesn't come up, I need help.

  • I have tried this tutorial for two domains, one success is done but other shows in the browser "Not Found". In the putty, when I use the command: sudo service apache2 restart to restart, I find this following message:

    AH00112: Warning: DocumentRoot [/var/www/MyDomainName.com/public_html] does not exist

    But fact is that, there is such of directory. Could you help me?

    • If apache says the folder does not exist, then either it is really not exist or may not be accessible by apache..
      maybe check permissions.

  • Hi,

    I am running UbuntuGNOME 14.04. At the end I get error.

    $ sudo service apache2 reload 
     * Reloading web server apache2                                                                                                      * 
     * The apache2 configtest failed. Not doing anything.
    Output of config test was:
    AH00526: Syntax error on line 3 of /etc/apache2/sites-enabled/www.conf:
    Invalid command 'SeverName', perhaps misspelled or defined by a module not included in the server configuration
    Action 'configtest' failed.
    

    Doens't matter if use:

    ServerName domain.tld
    

    or

    ServerName IP
    

    retrieved with

    $ /sbin/ifconfig -v eth0 | grep inet | awk {' print $3 '} | head -1
    

    Any idea?

  • I have 2 droplets created on digital ocean. Each droplet has a domain registered from 2 different registrars and both are pointing to DO nameservers (terminology?). So; two different domains, two different droplets, both working.

    I want to merge the two.

    On the 2nd droplet I followed the above directions. Since the 1st droplet's name servers were already pointing to Digital Ocean I thought all I would have to do remove the "A" record from it and add a another "A" record on the 2nd droplet.

    This is not working :(

    Is the CNAME on the 2nd droplet interfering with the resolution or maybe it takes some time to propagate?

    OMG, i just refreshed...so much confusion. Site 2 just came down!!!! that is real bad!!
    Site 2 is now loading up Site 1

    attempting to revert :(

    EDIT: revert successful....obviously putting both A records on one server is not the correct way to do it. tbh, I no longer need the 1st droplet, I can delete it, however, I want to make sure the domain will still bring up the site on the new server first though.

  • If I create a directory without public_html in last, is there any problem?

    sudo mkdir -p /var/www/example.com/public_html instead of this, I gonna create this one.

    sudo mkdir -p /var/www/example.com

    plz tell me if there is any problem

    • @bijuoosmail: No, that shouldn't be a problem. Just make sure that you reference that directory correctly within your Apache configuration files and you shouldn't have any problem.

  • If I want to setup the website content in a new location, such as /data/www, I may need to change apache2.conf. Please add this into this article. It will be helpful to users who want to do some customization.

  • Please also add a section and write about these two commands:

    sudo a2dissite example.com.conf
    sudo a2dissite test.com.conf

    It will help to my all friends who want to make changes after set virtual host.

  • Here i found one section missing.

    How to add DNS record of secondary domain ?

    Suppose i have two domain > default domain dom1.com and second dom2.com

    I added dom1.com DNS and setup Virtual host for dom2.com

    Now how to add DNS of dom2.com ?

    This should be in this article But please tell me.

  • I have a domain, mudhir.com and I've used dynDNS to make it point to my public IP address. And I've set it up in my router to use dynDNS.
    Now I've applied the tutorial and mudhir.com correctly displays my index file.
    However, it seems to be accessible only locally, when I try mudhir.com from a different network it doesn't work. Any ideas on what to do here, or pointers for the problem solution?

  • I try all the steps but it is not working. could you tell me the reason

  • Thanks. It works. Can I delete 000-default.conf and default-ssl.conf?

    • @cyanofresh: Yes, you can delete those files if you wish. Personally, I think it's usually a good idea to keep them around as a reference, but you don't have to keep them as long as they are disabled and not being used.

  • Very helpful article. Many Kudos.
    I was able to get example.com/test.com working inside my Ubuntu 14.04 VM as explained
    BUT from outside the System I cant access those site. my more detail question follows

    . Everything for webserver seems to be working fine. For example I have index.php page with

    <?php
    phpinfo();
    ?>
    inside /var/www/html & also under /var/www/mytestsite.com/ From inside the webserver, both sites @ http://MyServerIPAddress/hello.php & http://MyServerIPAddress/mytestsite.com/hello.php are working showing proper phpinfo.

    When I test the same from outside the server, I can only reach page inside /var/www/html http://MyServerIPAddress/hello.php But page access to http://MyServerIPAddress/mytestsite.com/hello.php Message shows

    Not Found
    The requested URL /example.com was not found on this server.
    Apache/2.4.7 (Ubuntu) Server at MyServerIPAddress Port 80.
    Here is mytestsite.com.conf I used for apache

    <VirtualHost *:80>
    ServerAdmin admin@mytestsite.com
    ServerName mytestsite.com
    ServerAlias www.mytestsite.com
    DocumentRoot /var/www/mytestsite.com
    </VirtualHost>
    And also matched folder access & owner setting to the match for both /var/www/html and /var/www/mytestsite.com

    What extra configuration DO I need to be able to access sites outside /var/www/html folder?

    • <Directory /var/www/mytestsite.com/html**/**>
      Options -Indexes +FollowSymLinks +MultiViews
      AllowOverride All
      Order allow,deny
      allow from all
      </Directory>

      There should be a slash at the end of directory location.

    • Still getting the same error.

      My host file is
      127.0.0.1 localhost
      127.0.1.1 ubuntu
      127.0.1.1 example.com

      New accessing from outside the WebServer using http://MyServerIPAddress/example.com/index.php

      What more can I do?
      What logs I can look/provide for debug?

    • 127.0.1.1 example.com example.com

      try above . my hosts file resembles like above ..

    • Tried but that change didnt work either..
      I looked at the Apache logs on the server
      When I access the page from inside server itself (and it works) I get the following
      http://localhost/example.com/index.php

      <MyServerIpAddress> - - [11/Jan/2015:15:17:40 -0800] "GET /index.php HTTP/1.1" 200 423 "-" "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36"
      

      BUT when I try from outside the server request coming in shows up as
      http://MyIpAddress/example.com/html/index.php

      <MyClientIpAddress> - - [11/Jan/2015:15:19:20 -0800] "GET /example.com/html/index.php HTTP/1.1" 404 523 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"
      
    • <MyClientIpAddress> - - [11/Jan/2015:15:19:20 -0800] "GET /example.com/html/index.php HTTP/1.1" 404 523 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 1095) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"

      So looking at that I changes my example.com.conf  DocumentRoot from /var/www/mytestsite.com to **DocumentRoot /var/www/**
      
      and that did the trick!!! 
      Here is the latest and working version of my for other peoples reference
      
      

      <VirtualHost *:80>
      ServerAdmin admin@example.com
      ServerName example.com
      ServerName 192.168.1.8
      ServerAlias www.example.com
      DocumentRoot /var/www
      <Directory /var/www/example.com/**/>
      Options -Indexes +FollowSymLinks +MultiViews
      AllowOverride All
      Order allow,deny
      allow from all
      </Directory>
      ErrorLog ${APACHELOGDIR}/error.log
      CustomLog ${APACHELOGDIR}/access.log combined
      </VirtualHost>

      
      Thanks for you support and advice.
      
  • I went through this verbatim and it won't work for me. I have two sites with the DNS pointing to my server, both are 'enabled' and have index.html files. Localhost works by giving me the default page but any attempts to access the other two sites, I get server not found errors.

    the sites are registered with godaddy. When I ping either URL, I get my server's IP address.

    Can anyone help?

  • Hi guys,

    Got a virtual site running, however i think i'm having a problem with .htaccess files, can you have an individual .htaccess per virtual site? i'm trying to run and site using the project from www.php-login.net (MVC Version), i've got the home page loaded but when using navigation the pages dont appear.

    any heklp would be grand.

    Simon

    • yes. .htaccess can be used for every invidual site. you need to allow Override when setting up the site in apache's sites-available directory configuration file..
      in your 000-default.conf ( or whatever it is )
      |_ in your site
      <Directory /var/www/>
      AllowOverride All
      </Directory>

      make sure you added the 'AllowOverride All'.

      reload apache - sudo service apache2 reload

      then try using .htaccess

  • I made a simple python script that will automate this process and will be able to create a virtual host automatically, this video explains how and here is the code (GitHub)

  • Thank you. I know how to do this all on windows, but not on ubuntu/linux :)

  • I'm getting a 403 forbidden message. Any idea what is wrong?

  • Hello, Great tutorial! I was just wondering how could I go about adding a new user to access the public_html folder (only) through ftp?

  • For those who still getting the default host pointing to /var/www/html here's the fix.

    Works fine for me.

  • hi i would like to ask if this tutorial can be used to create subdomain?
    i.e man.example.com

  • That didn't work for me. No idea how to access whether xxx.xxx.xxx.xxx/awesome.com or just awesome.com after creating virtual hosts. I couldn't visit by myself to that url so I end up creating something like that.

    ip/awesome.com/pulic ip/aweful.com/public
    That way I can create multiple sites without any additional changes.

    I enable home.conf which point to /var/www/html and
    with a small changes to apache2.conf like

    <Directory /var/www/html>
    Options +FollowSymLinks -Indexes
    AllowOverride All
    Require all granted
    </Directory>

    My unclear questions are

    1. If we can create virtual hosts like that, why do we need to buy domain like awesome.com?
      [ At this point, I created virtual hosts with digitalocean vps. ]

    2. After I creating virtal hosts like that, can I show my client with a link like awesome.com?

    Sorry if it's a stupid question.I'm just a junior.

  • Here's a quick script that will make this easy and painless. Let's say we call it "addsite" - place in /bin and call like this:

    addsite yourdomain.com

    Hope this helps!

    #!/bin/bash
    
    mkdir -p /var/www/$1/public_html 
    chown -R $USER:$USER /var/www/$1/public_html 
    chmod -R 755 /var/www 
    
    cp /etc/apache2/sites-available/default /etc/apache2/sites-available/$1 
    
    text="<VirtualHost *:80>
            ServerAdmin YOURNAME@YOURHOST.com
            ServerName $1
            ServerAlias www.$1
            DocumentRoot /var/www/$1/public_html
            <Directory />
                    Options FollowSymLinks
                    AllowOverride All
            </Directory>
            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>"
    
    echo "$text" > /etc/apache2/sites-available/$1 
    
    a2ensite $1 
    service apache2 reload
    
  • I have the following issue:
    I want to serve a Zend project on my droplet so my vitrual host file looks like this:

    <VirtualHost *:80>
        ServerAdmin someemail@gmail.com
        DocumentRoot "/var/www/<directory_in_www>/public"
        ErrorLog ${APACHE_LOG_DIR}/error.log
        ServerName blood-drop.com
        SetEnv APPLICATION_ENV "development"
        <Directory /var/www/<directory_in_www>/public>
            DirectoryIndex index.php
            AllowOverride All
            Order allow,deny
            Allow from all
        </Directory>
    </VirtualHost>
    

    In the public directory i have the file index.php. This virtualhost works on my local MAMP environment. However, here, after cloning the project from git and creating the virtual host and a a2ensite command on sites-available/<my_conf_name>.conf I would want to access <my_droplet_ip>/<directory_in_www>/public but that returns a 404. I forgot to mention that I have executed the reload/restart and the conf is present in sites enabled. And also set the DocumentRoot "/var/www/<directory_in_www>/public" in 000-default.

    Any suggestions would be greatly appreciated.

    Thanks!

    • @susanuradu: I'd take a look at the specifics of the 404 in the error log if you can. See if the user/group that the Apache process uses (www-data by default) has ownership or group access to the files in your home directory. If the files are in the correct location and the configuration file is correct, then often it's something on the operating system level with access to read the files or access them (do the parent directories have the appropriate permissions?). Those are the things I'd start to look at. Good luck!

  • I've a permission problem on my dedicated webserver, but I'm not able to understand what's I was doing wrong.

    Ubuntu 14.04
    Kernel 3.19.2
    Versione Apache 2.4.7
    Versione PHP 5.5.9
    mysql 5.5

    (all from official repository, except for kernel. It comes from vivid repository)

    I've installed apache2 and it starts with user
    www-data

    I've set a virtualhost
    /home/USER1/public_html
    (where chown is USER1:USER1)

    so If I install any CMS (like joomla, wordpress or phpbb)
    I got lot of permission's problem and I'm forced to set chmod to 777 (OMG! Against common sense)
    in order to install one of them.

    The "standard" chmod for this kind of CMS is
    755 for directory
    644 for files

    but if I set this kind of permission, I cannot do anything with the cms (install anythink or update it. Files will be considered unwritable).
    Same problem with 775
    So the problem is that my webserver needs all permission to "OTHER" and not just for USER (or at least fro GROUP)

    In order to avoid this trouble I've added USER1 to www-data group

    usermod -a -G www-data USER1
    

    but files still unwritable with 775 or 755. The only chmod allowed still 777 (OMG is orrible to write it 2 times in the same post )

    What is the problem?
    What I'd have to do in order to fix that trouble?

    Thank you for support

    • @virgy: Sorry to hear that you're having so many issues. What happens if, instead of adding your user to the www-data group, you add the www-data user to your group:

      sudo usermod -a -G USER1 www-data
      

      You should be able to get 775 permissions working at that point (remember to restart Apache).

      Let me know if that works.

  • That's awesome, thanks

  • I've "partially" fixed

    add www-data to user1's group
    chown user1:www-data public_html
    chmod g+s /home/user1/public 
    
    

    now it works fine ;)

    p.s. what about a guide for FastCGI and PHP.ini multiuser configuration?? :D

    Thank you for your guides ;)

  • How do we create a subdomain? I am trying to setup both mysite.com and test.mysite.com. Thanks for any help you can give!

  • Personally I wouldn't do sudo chmod -R 755 /var/www since that will make ALL files and folders inside /var/www executable. But I guess this is just showing the basics of it and the user should only have the /var/www/html/index.html file inside /var/www at that moment so it's not the biggest harm, but still, it's usually best practice not to make executable files that don't need to be executable.

  • Thanks a lot for this great tutorial. This helped me a lot to host many website into my doming www.felight.com

    But for some reason I want to remove a site. You can guide me the reverse process of it !! ??

  • For those who would need to connect their existing domain to the VPS, you have just to add an A record through your DNS management on the registrar and wait up to 24 hours to be updated (usually it takes just minutes or a couple of hours).
    Of course you have to use the VPS IP, in the tutorial case 111.111.111.111. :)

  • I encountered following problems when installing Apache2 and configuring it. I am using Elementary OS, Apache 2.4.7 installed. First problem was that enabling a site did not work, which was easily solved by adding file extension .conf to the virtual host config file.

    Second problem was that my domain did not resolve to my specified directory, but it did resolve to the default localhost configuration.

    In my /etc/hosts file I had both localhost and api.custom.com routed to 127.0.0.1. Missing /etc/hosts was not the problem.

    What was the problem is for some reason Apache did not like VirtualHost tag like this:
    <VirtualHost *:80>. I had this same tag for both virtualhosts, but with different ServerName/ServerAlias/DocumentRoot.

    So after reading through Apache2 docs a bit, I changed VirtualHost tag to <VirtualHost localhost:80> and <VirtualHost api.custom.com:80>, which did the trick. localhost and api.custom.com now resolved correctly.

    Hope this helps someone as this was pain in the ass.

  • This tutorial saved my sanity, but I still have a problem. The Default page and my new site are available on my new Ubuntu box, all good so far. I can also access the Default page from my windows boxes on the local network but my trying to get my new site gives 404 file not found.

    The access.log shows - [25/Apr/2015:16:22:34 +0100] "GET /CumulusWeather/ HTTP/1.1" 404 499 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36". CumulusWeather is the virtual host servername. The error.log shows nothing.
    Any suggestions would be helpful.

  • I keep getting the apache default page, here are my steps for a single site what am i doing wrong?

    sudo apt-get update
    sudo apt-get install php5-gd libssh2-php

    sudo mkdir -p /var/www/Mysite/publichtml
    sudo chown -R rami:rami /var/www/Mysite/public
    html
    sudo chmod -R 755 /var/www

    Create Demo Pages for Each Virtual Host

    nano /var/www/Mysite/public_html/index.html

    <html>
    <head>
    <title>Welcome to Example.com!</title>
    </head>
    <body>
    <h1>Success! The example.com virtual host is working!</h1>
    </body>
    </html>

    Create New Virtual Host Files

    sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/Mysite.conf

    sudo nano /etc/apache2/sites-available/photo.conf

    <VirtualHost *:80>
    ServerAdmin My email@live.com
    ServerName Mysite.com
    ServerAlias www.Mysite.com
    DocumentRoot /var/www/Mysite/publichtml
    ErrorLog ${APACHE
    LOGDIR}/error.log
    CustomLog ${APACHE
    LOG_DIR}/access.log combined
    </VirtualHost>

    Save and close the file.

    Enable the New Virtual Host Files

    sudo a2ensite photo.conf
    sudo service apache2 restart

    Could it be my Dns setup, do i have to add subdomain or something more complex, it's set up just to point here and thats it?

  • Hi there!

    perhaps someone can help me here.
    I followed up this tutorial very closely. Indeed everything went well. I added one domain at the time. However, as soon as I added second domain despite which domain name I punch in the browser, only the last added domain opens up.
    Let's say my first domain is test1.com and my second domain is test2.com (both are FQDs forwarded to my server's IP). I create test1.com and my browser opens up test1.com, than I create test2.com and my browser opens up test2.com only. Even if I type in test1.com, test2.com opens up...
    Also, instead of page domain name the IP address of my server shows up at browser's address line...

    I've been trying to get this thing sorted out for quite some time now, I'd appreciate any help please.

  • Fantastic, easy to understand tutorial, written in plain english, and with the highlighted areas that show what a user should change really easy to make work for a situation of your own :D

  • It is very important to note, that you need to disable 000-default.conf

    before
    sudo a2ensite example.com.conf
    sudo a2ensite test.com.conf

    do

    sudo a2dissite 000-default.conf
    
  • Very helpful. Thanks!

  • Is perfect but i need access to www.domain.com and domain.com (Internet explorer), but in domain.com enters to default page of apache.

    www.domain.com.conf

    <VirtualHost *:80>
    ServerAdmin domain@domain.com
    ServerName ejemplo.com
    ServerAlias www.ejemplo.com
    DocumentRoot /var/www/ejemplo.com/publichtml
    ErrorLog ${APACHE
    LOGDIR}/error.log
    CustomLog ${APACHE
    LOG_DIR}/access.log combined
    </VirtualHost>

    • Why not:
      <VirtualHost *:80>
      ServerAdmin domain@domain.com
      ServerName www.ejemplo.com
      ServerAlias ejemplo.com
      DocumentRoot "/var/www/ejemplo.com/public_html"
      ErrorLog ${APACHELOGDIR}/error.log
      CustomLog ${APACHELOG_DIR}/access.log combined
      </VirtualHost>

      ?
      Please pay attention I changed as well publichtml for public_html.

  • Thanks for the tutorial. Do I need to edit /etc/hosts on my droplet to add $MY_IP mywebsite.com after all configurations?

  • Hi all, when i try to load the website address (mine is http://test.project.com) i get these as error message. What did i do wrong? is it the name? should i only have put something like project.com only?

    Error Code 11001: Host not found
    Background: This error indicates that the gateway could not find the IP address of the website you are trying to access. This is usually due to a DNS-related error.
    Date: 6/23/2015 7:09:53 AM [GMT]
    Server: GOC-SVR-TMG-02.goc.local
    Source: DNS error 
    
  • Well, I have been trying all these solutions offered..but sadly nothing worked! Alas i edited

    /etc/hosts
    

    to make entry

    127.0.1.1 example.com test.com
    

    and it worked!!

    (Sorry if I'm not talking much technically!)

  • If you find that Apache is still returning your default host content and not the content of your new virtual host you might not have restarted apache using sudo.
    Try sudo service apache2 restart and see again.
    This caught me out ;)
    Brad

  • Im getting forbidden all the time. no permission to access /index.php. But my permissions for index.php are set.

  • Great info, thanx

  • There's a missing command in the instruction:

    sudo a2dissite 000-default.conf
    
  • nice tutorial ...

  • Hey everyone sorry if these are obvious questions but here I go.
    I have two domain names pointing to the same droplet.

    1.) If I create just one new configuration and leave 000-default as is, can I leave my main site under www/html and have my other site be virtually hosted at www/othersite/publichtml?

    2.) Secondly if create two configurations, move all my contents from www/html to www/mainsite/publichtml, and call a2dissite on 000-default.conf will all my search rankings in Google remain in tact or will something get reset.

    Sorry again if this is basic knowledge, I'm just a bit nervous to go through it since the main site has some daily visitors and decent search placement.

  • Thank you for your excellent tutorial. I note that Step 6 is not optional but necessary to make my virtual host work and in fact I have to add two additional lines to /etc/hosts file then only it is functional. My modified file appears as follows:

    127.0.0.1 localhost
    127.0.0.1 example.com www.example.com
    127.0.0.1 test.com www.test.com
    127.0.1.1 guest-desktop
    111.111.111.111 example.com
    111.111.111.111 test.com

    Thank you.

  • It's been awhile since I've done this before, but I just added my 5th virtual host and after restarting apache I got the error:

    "*Starting web server apache2

    The apache2 configtest failed. Output of config test was: apache2: Syntax error on line 216 of /etc/apache2/apache2.conf: Could not open configuration file /etc/apache2/conf-enabled/charset.conf : No such file or directory
    Action 'configtest' failed."

    Can anyone help?

  • Great tutorial i just needed to add folders for virtual hosts in apache2.conf file.

  • My Apache setup script automates all this, and goes the extra step of self-signed certificates for HTTPS.

    https://github.com/jaredevans/setup_multiple_apache_websites
    
  • Did the expression create virtual host is the same expression that add domain in the cpanel, the feature add new domains to my hosting but in command line .. that's it that's add domain?
    because when webmin used, in time to add new domains to new sites and the same expression is used here ... create virtualhosts. I want new sites, new domains via command line, I know with nginx, apache i dont now.

  • What a wonderful tutorial. Thanks a lot for the info, Justin!

  • "ERROR: site does not exist"

    Whats happened? help me please.

  • Hi, in the process off learning all this from scratch i wrote a tutorial for setting up multiple Wordpress sites which people may find helpful, some things are missing from the digital ocean tutorials which are included here.

    Setting-up-3-wordpress-sites-on-Apache-server-and-Ubuntu-14-04

    https://sunnahmuakadasupplementary.files.wordpress.com/2015/09/setting-up-3-wordpress-sites-on-apache-server-and-ubuntu-14-04.pdf

  • I got through it all and amazed but then now I'm stuck to how I connect those new directories to domains, searched everywhere and it seems like theres no straight answer to it. Can anyone walk me through that please?

  • this was easy and awesome! thx!

  • Great tutorial thanks this was helping me to get my domain to work!

  • Just a bit suggestion for this tutorial for other readers:

    • there are many sudo in this tutorial because the dire /var/www requires root permission
    • therefore I modified the permission of /var/www to the user account I was using
    • If you know what you are doing, try sudo chown user_name /var/www
  • Thanks for this, set me up pretty easily, i only have one problem though. I came from xampp background on windows, and i copied the same folder, and followed this structure. I was able to get the page working, just my homepage, but the other pages wont work. it says The requested URL /ajibak.com/publichtml/aboutus was not found on this server. I specified the path in my folder like this. define('URL', 'http://localhost/ajibak.com/public_html/');. Can anyone help me out, as i feel my problem as to deal with me not specifying the path well. any help will do. Thanks

  • Just gotta say thank you for one of the best walk-throughs I've experienced. Everything in this article is important and there is no useless information. Really nicely designed too, light colors and good spacing. Thank you!

  • thank you thank you thank you!!!

  • Would it be possible to write a shell script to do this? I used to write them in college but its been years. Maybe you're aware of the existence of one? Thanks! -Brian

    UPDATE: I found this script here that seems to work well.

  • Works like a charm... It's amazing. Thank you Justin.

  • nice tutorial , it's work for me !

  • I had to run sudo service apache2 restart in order to get this working because service apache2 reload did not work.

  • Hi Justin,
    there is a typo, you wrote "we will create a public_html file" but meant FOLDER :)

  • Great, it works fine.

  • Hey! I followed all the steps successfully but I could only get one domain working (pedrothe.ninja). The other one is not working (notmyissue.co).

  • i am using filezilla to copy some files on my server, but i can't see the /var/www/example.com/public_html on it. How do i see it?

  • I need some help. I installed apache2 on ubuntu 14.04 and configured 2 dummy virtual host as the tutorial above: all the steps runs properly, but when i want to test if the hosts worked properly(such as example.com) the page isnt opening as the HTML.
    How can i be sure that my host are running properly.
    I want to use these hosts to test an SSL connection using "letsencrypt"
    Thanks in advance for your support

    • @eliasantoun90: Before you go any further, you should know that Let's Encrypt will not work with dummy domain names. You must use a legitimate domain name that correctly resolves to your server's IP address in order for the tool to work correctly. If you are having trouble with the dummy values used in this guide, consider purchasing a domain name if your purpose is to eventually use Let's Encrypt.

  • That's a really nice article image of Apache.

  • If i Edit index.html file it does not take effect what to do.. what if i want to access these files from my windows7 Pc if im in Local area network

  • Thanks! Now none of my sites are workiing!! :(

  • You mention the following message will appear after restarting:

    * Restarting web server apache2
     AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message
    

    I'm wondering how we should go about suppressing the message?

  • Great article. I am able to follow the steps and reach to conclusion. What I think left is, we are able to open site using example.com but www.example.com is not working.

    Can you help or atleast point in right direction.

  • Hey, question, once I have set this up I would like to somehow transfer files from my computer to the server, how would I go about it? Which would be the more easy way for a beginner? Filezilla?

  • Hey,

    I am having a problem where the subdomain would load properly but the main one displays the Default apache 2 page, I have followed the tutorial closely and done it two times, but I can't resolve my issue, what could be the thing that I am overseeing? Can't figure it out.

  • Very helpful thank you!

  • Great tutorial! It worked perfectly, thank you Justin.

  • Thanks for the awesome tutorial,
    I have already configured zend framework 2 on my system and its running well, Now when am trying to set the new virtual host after following all the steps it says test.com not found/ time out error.

    Can you please guide me if I need to do any more changes.

  • i didnt get the sixth step in which we have to add that vps address
    I'm stuck on that part

  • For step 6, I used the public IP address of the computer I'm running Apache on. Is this correct? When I go to example.com, it just times out. I'm using Ubuntu 14.04.

  • it works with test.com but it doesn't work with example.com, this is the output when i try to load
    http://example.com

    Example Domain

    This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.
    More information...

  • First off I'd like to say awesome tutorial!!!

    I was however hoping that you might know why the ServerAlias doesn't seem to work for me. The site works as http://mysite.com however http://www.mysite.com yields a Cannot find Server Error.

    Below is my vHost Configs:

    <VirtualHost *:80> 
        ServerAdmin admin@mysite.com
        ServerName mysite.com
        ServerAlias www.mysite.com
        DocumentRoot /var/www/html/mysite.com/public_html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    
    <VirtualHost *:443>
            DocumentRoot /var/www/html/mysite.com/public_html
            ServerName mysite.com
            ServerAlias www.mysite.com
            SSLEngine on
            SSLCertificateFile ssl/mysite.crt
            SSLCertificateKeyFile ssl/mysite.key
            SSLCACertificateFile ssl/bundle.crt
    </VirtualHost>
    

    Any ideas?

  • Is there a post like this explaining same process with use of port 443 and wildcard SSL certificate?

    I have www.somesite.com as master domain
    then subdomains for api.somesite.com and wp.somesite.com
    Also I have one *.somesite.com SSL certificate.
    But only https://www.somesite.com/ works as intended.
    api.somesite.com and wp.somesite.com work fine on port 80 only.
    Meaning http://api.somesite.com and http://wp.somesite.com point where I want them to point to.

    But, if I go through 443 using SSL certificate https://api.somesite.com and https://wp.somesite.com they will point me to https://www.somesite.com instead.
    What is the correct config for virtual hosts. I think I tried everything and still I am not where I want to be.
    Thanks

  • Had a question. What is the point of the ServerAlias line if you can use DigitalOcean DNS records to redirect using cnames? To clarify, is there a difference between creating a cname using the control panel or using the .conf file to declare server aliases? New to this stuff, sorry if my question seems silly.

  • I'd be interested in hearing more about the recommended configuration of file permissions with regard to security. I can host multiple hosts on a single server, great! But I want to do all I can do to ensure a vulnerability in one site doesn't affect others.

  • Is there a working tutorial for hosting multiple SSL websites on one Ubuntu 14.04 server and one IP using SNI. The tutorial that is available is for Ubuntu 12.04. If one follows the instructions, it does not work on 14.04 as ports.conf does not need to be touched for 14.04. The Listen directive also creates errors. The certificate error appears but the website des not go ahead after accepting the certificate. Apache error logs or access logs do not show any error.

  • Hi Guys first all thanks for this tutorial however im currently struggling big time :( to test both my websites and not sure exactly sure whats going on....im currently running My Ubuntu 14.04 LTS on Linode manager, i followed all the steps as described but when it comes to Enable the New Virtual Host Files, i get the errors below:

    root@olivierubuntu:~# a2ensite olivierubuntu.com.conf
    ERROR: Site olivierubuntu.com does not exist!
    root@olivierubuntu:~# a2ensite test.com.conf
    Site test.com already enabled

    I checked and olivierubuntu.com.conf does exist
    root@olivierubuntu:/etc/apache2/sites-available# ls
    000-default.conf default-ssl.conf <Help>! olivierots.com.conf test.com.conf
    root@olivierubuntu:/etc/apache2/sites-available#

    when i test http://test.com, its taking me to a diff website :(

    Can someone please help? many thanks. let me know if you need any other info

    /etc/host & hostname looks like this:

    root@olivierubuntu:/etc/apache2/sites-available# cat /etc/hostname
    olivierubuntu
    root@olivierubuntu:/etc/apache2/sites-available# cat /etc/host
    cat: /etc/host: No such file or directory
    root@olivierubuntu:/etc/apache2/sites-available# cat /etc/hosts
    127.0.0.1 localhost
    127.0.1.1 olivierubuntu ubuntu
    8.8.8.8 google.com
    111.111.111.111 olivierubuntu.com
    111.111.111.111 test.com

    The following lines are desirable for IPv6 capable hosts

    ::1 localhost ip6-localhost ip6-loopback
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
    root@olivierubuntu:/etc/apache2/sites-available#

    some errors in the log

    root@olivierubuntu:/var/log/apache2# tail -n 10 error.log
    [Mon Apr 18 21:56:59.353393 2016] [mpm_event:notice] [pid 4772:tid 140273817315200] AH00489: Apache/2.4.7 (Ubuntu) configured -- resuming normal operations
    [Mon Apr 18 21:56:59.353485 2016] [core:notice] [pid 4772:tid 140273817315200] AH00094: Command line: '/usr/sbin/apache2'
    [Mon Apr 18 22:04:04.717684 2016] [mpm_event:notice] [pid 4772:tid 140273817315200] AH00491: caught SIGTERM, shutting down
    [Mon Apr 18 22:04:58.704324 2016] [mpm_event:notice] [pid 3442:tid 139676373403520] AH00489: Apache/2.4.7 (Ubuntu) configured -- resuming normal operations
    [Mon Apr 18 22:04:58.704826 2016] [core:notice] [pid 3442:tid 139676373403520] AH00094: Command line: '/usr/sbin/apache2'
    [Mon Apr 18 22:35:23.542087 2016] [mpm_event:notice] [pid 3442:tid 139676373403520] AH00491: caught SIGTERM, shutting down
    root@olivierubuntu:/var/log/apache2#

  • I am thankful for this excellent tutorial, but also a little puzzled it doesn't address the need for Apache to write to directories and/or create files in the document root - this is a common requirement for any kind of CMS-based site such as Drupal, Wordpress, Joomla etc.

    If the public_html directory is owned by $user:$user as explained in Step2 of the tutorial, how can Apache (which runs as www-data on Ubuntu) write to/create files and directories inside it?

  • everything done nicely, why its showing me ngix welcome page?

    VirtualHost configuration:
    *:80 is a NameVirtualHost
    default server 127.0.1.1 (/etc/apache2/sites-enabled/000-default.conf:1)
    port 80 namevhost 127.0.1.1 (/etc/apache2/sites-enabled/000-default.conf:1)
    port 80 namevhost codepharmacy.com (/etc/apache2/sites-enabled/mysite1.com.conf:1)
    alias www.mysite1.com
    port 80 namevhost harmandirsahib.info (/etc/apache2/sites-enabled/mysite2.com.conf:1)
    alias mysite2.com
    ServerRoot: "/etc/apache2"
    Main DocumentRoot: "/var/www"
    Main ErrorLog: "/var/log/apache2/error.log"
    Mutex default: dir="/var/lock/apache2" mechanism=fcntl
    Mutex mpm-accept: usingdefaults
    Mutex watchdog-callback: using
    defaults
    PidFile: "/var/run/apache2/apache2.pid"
    Define: DUMPVHOSTS
    Define: DUMP
    RUN_CFG
    User: name="www-data" id=33
    Group: name="www-data" id=33
    Welcome to nginx!

    If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

    For online documentation and support please refer to nginx.org.
    Commercial support is available at nginx.com.

    Thank you for using nginx.

    don't know what went wrong?

    Please help
    Thanks

  • i do that same as your articles but i got same page on both website .plz help me

  • I started the LAMP guide before i came into this guide, everything seems to work fine...however, how do i manage the original main /var/www/html directory that is accessible via the IP? Should i remove folder, or redirect it to a vhost directory? And how would i do any of those...

  • Thank you for the great tutorial. We need to set-up several thousand domains for redirect. Do you know of some way to automate this from a database?

  • Very helpful article! I was able to setup my virtual host perfectly. I'm just wondering if it's possible to have multiple HTTPS site as well. Right now, it seems to always use /etc/apache2/sites-available/000-default-le-ssl.conf. Is there a way that when a site is accessed via HTTPS, it will still follow the DocumentRoot of a vhost?

  • Hi thank you great tutorial and works perfect i was woundering though.. so i can set up mutliple website and one website is not for mine but how do i set up a mysql/phpmysql account for that person and how does it work with her web root directory?

  • Thank you very much. Your guide help me a lot, also this article will help me a lot
    digital ocean virtual hosts on vps

  • When creating a virtual host, would the procedure be the same if I wanted to do it with a subdomain? I set up the root domain successfully, but it doesn't seem to work when I try to do a subdomain.

  • Hi, I'm stuck on the step on "ServerAdmin". I'm typing the command but my mac says,"ServerAdmin: command not found"... What can I do??

  • Great article, concise and accurate. Thank you.

  • I folowed this tutorial, add 3 domains, i have only 2 question:

    1 - In the end of the process, i need to delete the "000-default.conf"???

    2 - In the end of the process i geting the "Server error 500" in all domains, why?

    Thank you.

  • You forget to dissable default configuration by comand

    sudo a2dissite 000-default.conf

    All works fine.

    here is page with more information for debian 8

  • Did all the steps but my subdomain is redirected to the main domain. Is this maybe because of SSL on my main domain? How to set it? Thanks!

  • show how to grant

  • I deleted one of my files located in /etc/apache2/sites-available and /etc/apache2/sites-enabled. Is there any way I can recreate the file in order to access the website again?

  • Hi,
    That's a real wow, informative article written so clearly with each step outlined. I must have gone through at least 20 posts and articles but failed to achieve what your article helped me achieve in the very first go ! Thanks so much.

    I do have a question though. All is working fine. My project has a restricted folder called restricted, that must be placed out side the root and whose permissions are different from the rest of the /vagrant folder. I know these permissions can only be set from the vagrantfile and i set them as
    config.vm.syncedfolder ".", "/vagrant",
    owner: "vagrant",
    group: "www-data",
    mount
    options: ["dmode=775,fmode=664"]

    These are, however, set for the entire /vagrant folder and all sub folders and files in it. How can I selectively change the settings for the restricted folder to say
    mount_options: ["dmode=750,fmode=640"]

    Thanks loads for the great tutorial once again.

  • Great guide, You made my day, thank you so much :)

  • Replace all

    <Directory />
    AllowOverride none
    Require all denied
    </Directory>
    with

    <Directory />
    AllowOverride none
    # Require all denied
    </Directory>
    hence removing out all restriction given to Apache.

    Replace Require local with Require all granted for the C:/wamp/www/ directory.

    <Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
    # Require local
    </Directory>

    i have problem with directory "permmission denied" and always refer to /var/www/html.

    reference : http://stackoverflow.com/a/38031212

  • Hi ,
    Actually i have followed all the steps but then the page is not working

    Thanks in advance

  • Thumbs up for the great guide for setting up virtual hosts!

    I am creating my virtual host on an Ubuntu 14.04.3 server, by way of remote access (putty) from a Windows PC.

    I followed the instructions from this guide and was almost there. I was able to access my index.html file WHEN I add the IP (xxx.xxx.xx.x) together with the website address (example.com) on client PCs' hosts files:

    xxx.xxx.xx.x    example.com
    

    However, without the modification shown above, I was greeted with a "Server not found" page in Firefox, and the like in other browsers.

    Anyone being hit with this? I would really appreciate any pointers.

    Thanks.

    • Sorry, my bad!
      I had to play around with the permissions to get it to work. :D
      Thanks.

  • I'm trying to create a subdomain WordPress multisite so I create a separate vhost for my subdomain that points to my domain's directory in apache but when I type in subdomain.example.com it goes to the root of the apache server.. if this is happening, what configuration did I do wrong?

  • sangat bermanfaat, terima kasih

  • What I really can't understand is this: when I change my local /etc/hosts configuration, I understand that if I make a request to test.com (for example), it will be changed by 111.111.111.111 ip, even before going out of my local machine.

    How does apache know whether site to choose? (when it is only getting a GET request to 111.111.111.111).

    I guess I'm totally wrong at some point.

    Thanks in advance!

    • @nanocv In an HTTP request, the requested host or domain name is encoded within the "Host" header. Before the client or browser can send the request to the appropriate server, it needs to resolve that name to an IP address so that it can establish a TCP connection (HTTP requires a reliable underlying connection, which almost always means TCP). We need the IP address and port because the TCP protocol does not understand domain or host names.

      The /etc/hosts file is responsible for providing name and IP mappings similar to a simplified DNS A or AAAA record query. The process of looking up the IP address of the service in question happens before the actual HTTP request is made.

      Once the IP address is known, the client establishes the TCP connection to the IP address it discovered. It then sends the original HTTP request, which still has the domain name in the "Host" HTTP header, to the server over the TCP connection. Apache then checks the "Host" header to see which virtual host should be selected.

      So the "Host" header is used by the client to determine where to establish a TCP connection using DNS or by checking the /etc/hosts file. However, the header itself is not altered and it's forwarded to the server intact.

      Hope that helps!

  • I've done exactly as said above but my website keeps loading until it gets a connection time out. My domain and virtual hosts configuration are fine and there's nothing on apache error log files. What can it be?

  • Hello,
    I setup all things correctly but still sometime IP address showing in google search.
    http://prntscr.com/gizyse
    I dont know where is the mistake,
    https://prnt.sc/gizi52
    http://prntscr.com/gizihf

  • Hi guys,

    I am not really a developer but I was able to get this far in terms of setting up my account and getting two domains hosted on one server. I followed this tutorial step by step and I got no error messages but it looks like both my domains refer to the index file in '/var/www/html/index.html' instead of the respective directories like '/var/www/domain.com/public_html/'.

    In my virtual host files for each of the domains, I have the DocumentRoot specified to be /var/www/domain.com/public_html/ but despite that both domains show the same file from /var/www/html/index.html.

    I have also disabled the 000-default.conf file.

    Any idea what I maybe doing wrong?

  • Hello Justin

    Your tutorial was very helpful. Thank you ! God Bless you

  • this article is just wunderfull thanks verry much

  • Hi and thanks for the great tutorial.
    I'm running a website with Grav that requires Nginx.
    How can I possibly create a subdomain if I need to run apach2 and nginx?
    In doubt I follow your steps and I got stuck at sudo service apache2 restart.
    It seems it can't start apache and the apache error.log is empty.
    What do you suggest?

  • Hi,

    Is this the correct way to start setting up subdomains as well?

    Would this be correct?
    sudo mkdir -p /var/www/sub.example.com/public_html

  • This is great. I am going to try this out today. Just two questions:

    1. Will this work on Ubuntu 16.04 also? Any dependencies on particular libraries, versions, etc?
    2. I have 2 wordpress sites and 2 sites with just static pages. How do I go about it? Thanks for help!
  • cant get past the virtual host configuration to install wordpress. nothing from multiple tutorials works. i have so many different files i dont know whats what anymore. using server 16.04. was getting blocked by apache page, now just a 404.

  • very helpful topic its help me to create my all droplet.

  • i can go to my own IP and it shows the index.html that i've created.
    but why it wont goes with my servername / serveralias ?

    and does this configuration makes my server become public? if it doesnt, how to make it? i tried go to my IP from my phone browser.

    • did you set up your name servers? They are what translate the domain name to the ip.

  • Hello! The tutorial is clear to me and I have a bit of experience on this kind of configuration, but when I try to visit example.com, after all the configuration the page return a "ERRCONNECTIONTIMED_OUT".
    My droplet is an Ubuntu 16.04.4, what I'm doing wrong?
    Thank you for support!

  • Hello,

    I originally have a wordpress site installed on my droplet. After following all the steps here, I'm now stuck at being shown the image in step 7. How do I change my preferences so that I can go back to seeing my wordpress site when I enter that domain in my browser?

    Thank you!

    UPDATE: Fixed it- just moved my old html file to under thecollegedorm.com, remove publichtml, rename old html file to publichtml.

Creative Commons License