How to Configure Apache Web Server on Linux

July 26, 2009 by
Filed under: HowTo, linux, web development 

I've shown previously how to install a LAMP server in Ubuntu. If the purpose of your LAMP installation was to set up your own web development environment, then you may want to do some further configuration to your system. This Apache howto is not intended to cover Apache configuration in depth. This is just some basic configuration to help you set up a web development environment in Linux. For more information, see the official Apache documentation.

Why Change the Apache Configuration?

By default, Apache is set up for your web site's files to be in the /var/www directory. This is fine if you only want to work on one website and access it through http://localhost/. But what if you want to work on several websites at the same time? Well, one solution is to create different directories under /var/www like /var/www/site1 and then access it through http://localhost/site1/. I prefer a more elegant solution.

I prefer to build websites in a directory under my own ID. I can then configure the Apache http server to point to the site directories with URLs like http://site1/, http://site2/, etc.

Creating a Web Development Directory

Lets start off by creating a folder structure for the development environment. You can do this from your file manager. I prefer the terminal.

cd
mkdir webdev
cd webdev
mkdir site1 site2

We now have a directory called webdev under our home directory. Within the webdev directory are two directories called site1 and site2.

Create Some Test Files

Now we're going to create some basic test files so that we know our Apache configuration worked. Again, I'm going to use the terminal to create these files, but feel free to use your favorite text editor.

cd ~/webdev/site1
echo 'Site1 works!' > index.html
cd ../site2
echo 'Site2 works!' > index.html

Enable the Sites in Apache

OK, we're now ready to do the actual Apache configuration. Go to /etc/apache2/sites-available.

cd /etc/apache2/sites-available

As root, copy the default file as site1.

sudo cp default site1

Repeat the process to create a site2 file.

As root, edit the site1 configuration file.

sudo nano site1

Edit the file to look like this (the changes are in bold).

<VirtualHost *:80>
	ServerAdmin webmaster@localhost
        ServerName site1

	DocumentRoot /home/yourID/webdev/site1/
	<Directory />
		Options FollowSymLinks
		AllowOverride None
	</Directory>
	<Directory /home/yourID/webdev/site1/>
		Options Indexes FollowSymLinks MultiViews
		AllowOverride All
		Order allow,deny
		allow from all
	</Directory>

	ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
	<Directory "/usr/lib/cgi-bin">
		AllowOverride None
		Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
		Order allow,deny
		Allow from all
	</Directory>

	ErrorLog /var/log/apache2/error.log

	# Possible values include: debug, info, notice, warn, error, crit,
	# alert, emerg.
	LogLevel warn

	CustomLog /var/log/apache2/access.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

</VirtualHost>

Note: The line that changes AllowOverride None to AllowOverride All is required if you want to enable URL re-writes through a .htaccess file. You need this if you want to utilize pretty permalinks in WordPress.

You now need to enable your new site.

sudo a2ensite site1

You should get a message telling you that you need to reload Apache to activate the new configuration. But first you need to edit your /etc/hosts file.

sudo nano /etc/hosts

Edit the first line adding site1 to the end of the line so it looks something like this and save the file.

127.0.0.1 localhost site1

You can now reload Apache.

sudo /etc/init.d/apache2 reload

Site1 is now enabled. Check it by browsing to http://site1/. If everything worked right, you should see a web page that says "Site1 works!"

Repeat the procedure to enable site2, etc.

Edit 12-Dec-09
If you get an error like “apache2: Could not determine the server’s fully qualified domain name, using 127.0.0.1 for localhost,” you can fix it with this command.

echo "ServerName localhost" | sudo tee /etc/apache2/conf.d/fqdn

Then, reload Apache to eliminate the error.

sudo /etc/init.d/apache2 reload

Comments

190 Responses to “How to Configure Apache Web Server on Linux”

  1. roy byer says:

    Hello there

    I have followed the tutorial and it seemed to work on the command line but when I tried to access http://site1/ i get 403 forbidden
    You don't have permission to access / on this server.
    where did I go wrong.
    regards

    roy

  2. Korouu says:

    Hey man! You are too great! What others cannot do, you have done. Now my long time desire has become possible because of your tutorial. And thanks to the almighty for showing me to this website.

  3. Pragasan says:

    Hi Linerd

    Thanks for the tutorial. I'm a newbie trying to set up my own ubuntu linux server for a production enviroment to host some of my applications. Is the setup tutorial for lamp and apache suitable for production environments? Also if we want to keep Ubuntu lamp installation up to date is there a command that we use?

    Thanks again for the great tutorial.

    • Linerd says:

      Hi Pragasan - I'm confident that the LAMP setup would be fine for a production environment. The Apache configuration, I'm not sure. I know little more than what I've documented on this website. I'm not sure that I've followed best practices for Apache, but the setup here works well for an offline development environment. I'd encourage you to consult the Apache documentation if you want to set up a production environment.

      As far as keeping things up to date; if you're running Ubuntu Desktop, then the update manager should keep you up to date. Otherwise, you can update your system with

      sudo apt-get update
      sudo apt-get upgrade
  4. James says:

    I installed LAMP on a setup of Ubuntu 10.04 and added the site1 site2 environments exactly as you show. Both sites worked just as you described. I have started using site1 to follow a series of tutorials on php.

    I have run into a problem and am baffled. Using firfox, I can got to localhost/site1 and call the index.html page and see the "Site 1 works!" in the browser
    I have copied the testing.php into site1 and when I call the page it gives me the php page, so I know that apache is serving up php from site1 as well.

    I have built the following page called index.php which calls for a MySQL database called gwdb and a table in the database called guitarwars. I have written the code exactly as it is written in the tutorial changing only the location of the database to site1 in the call to connect to the database; $dbc = mysqli_connect('site1','root', 'password', 'gwdb')

    All I am getting in firefox is a blank page. In chromium web browser I am getting "Oops this link appears to be broken"

    I am new to Linux and PHP and trying to learn and I can't see what is causing this break in the link. I have included the code below:

    
    <html xmls="http://www.w3.org/1999/xhtml"
    xml:lang"en" lang="en">
    
    <head>
    <title>Guitar Wars - High Scores</title>
    <link rel="stylehseet" type="text/css" href="style.css" />
    </head>
    <body>
           <H2>Guitar Wars - High Scores</h2>
           <P>Welcome, Guitar Warrior, do you have
           what it takes to crack the high score list?  
           If so, just <a href="addscore.php">add
           your own score</a>.</p>
           <hr />
    
    <?php
           // Connect to the database
           $dbc = mysqli_connect('site1','root', 'mailbox1823', 'gwdb')
                   or die('Error connecting to database');
    
           // Retrieve the score data from MySQL
           $query = "SELECT * FROM guitarwars";
           $data = mysqli_query($dbc, $query);
                   or die('Error quering database');
    
           // Loop through the array of score data, formatting it as HTML
           echo '<table>';
           while ($row = mysqli_fetch_array($data)) {
                   // Display the scare data
                   echo '<tr><td class="scoreinfo">';
                   echo '<span class="score">' . $row['score'] . '</span><br />';
                   echo '<strong>Name:</strong> ' . $row['name'] . '<br />';
                   echo '<strong>Date:</strong> ' . $row['date'] . '</td></tr>';
           }
           echo '</table>';
    
           mysqli_close($dbc);
    ?>
    
    </body>
    </html>
    
    
    • Linerd says:

      James - I edited your comments into one to capture the spirit of what I think you were trying to show.

      I'm no php pro, so I doubt I'll be much help. I did try your file on my machine and it doesn't load. The file does work if I remove the php portion. Maybe another reader can offer some advice.

    • David says:

      in your mysqli_connect statement you should still be using localhost not site1 because the mysql server is on localhost.

  5. James says:

    Linerd,

    Thanks for cleaning up the comments. I fixed the issue. I had the database call parameters typed as strings ( ' ' ) by removing the single string quotes I was able to get the database to connect and the page would then load.

    Thanks again for the tutorial to set up the multiple web application development environment for apache.

  6. Jeff says:

    Awesome post! It worked great!

  7. DINESH BHATT says:

    I NEEDED SOME MATERIAL TO FINISH MY REPORT ,I THINK I GOT IT THANK U

  8. Ryan says:

    Fantastic post!!!!
    I managed to get this working so if I VNC onto my ubuntu desktop server I can visit http://site1/ no problems but if i try from my laptop I get an error... should I be adding site1 to the second line of /etc/hosts @127.0.1.1 instead of 127.0.0.1 localhost?

    Thanks a million

  9. Ryan says:

    Just found the hack under the older posts...sorry should have checked there first

  10. Rudy says:

    Is the configuration the same if using a no ip tool like NO-IP?
    I cannot reach any of the 2 sites when using the NO-IP URL (.syte.net).
    I tried adding the following entry in /etc/hosts:
    192.168.1.100 site1 site2
    (192.168.1.100 being the IP address of my Linux box)
    Although, if using the URL .sytes.net, I do reach the 'It Works!' Apache test page from my webserver.
    Any help would be greatly appreciated.

    Thx!

    • Linerd says:

      Rudy, I haven't tried this setup with a dynamic DNS setup. I'm thinking you would most likely have to modify the Apache configuration. However, it might work like it does when accessing the host machine web server from a VirtualBox guest. Have you tried __.sytes.net/site1 or __.sytes.net/site2?

      • Rudy says:

        Linerd,
        Thx for the quick reply.
        Yes I did try __.sytes.net/site1 or /site2 without luck.
        I actually figured it out. I had to disable the default config under /etc/apache2/sites-available by using the 'a2dissite' command (sudo a2dessite default).

  11. Rudy says:

    Actually, I do have to add that it will only allow __.sytes.com to point to one of the site and it will not work in a __.sytes.net/site1 and __.sytes.net/site 2 way.

    Still need to figure out this one.

  12. Lee Boone says:

    is there a way for other machines on a local network to view these sites? I can view the /var/www/index.html page using either the ip address (http://192.168.1.100) or the name (http://linux-box) of my linux machine, but can't seem to find the custom sites. (Which work perfectly on the linux computer, thank you)

  13. noip says:

    Thanks for the tutorial. Just wish I understood how those commands worked. :) I've set up WAMP several times, but this is my first LAMP.

  14. Bobot says:

    Hi Linerd,

    I just had a fresh install on a new HDD and followed your tutorial for the third time and it worked again.

    Muchas gracias

    Bobot

  15. Patrick says:

    Hi Linerd,

    Great tutorial, finally managed to get two sites going on a LAMP server.
    This may be a stupid question, but how do i get to the sites without modifying the hosts file, what address?
    I've tried the obvious http://localhost/site1 & http://localhost/site1/index.html

    • Linerd says:

      Hmm... I gave this a try and http://localhost/site1/ works for me. Did you make sure to enable the sites? Did you make sure to reload Apache?

      sudo a2ensite site1
      sudo /etc/init.d/apache2 reload

      Edit: Interesting, I just added the sites back to my hosts file and the change wouldn't take until I did a full restart of Apache, so maybe that's the trick to get it working for you.

      sudo /etc/init.d/apache2 restart
      • Patrick says:

        Hi Linerd,

        Thanks for the quick reply. I tried restarting Apache - no joy, I even tried undoing the fqdn fix you posted in case that was affecting it - no joy.

        Turns out to be able to access site1 & site2 via http://localhost/site1/ or http://localhost/site2/ I needed to put the site1 & site2 folder under /var/www/ as opposed to /home/patrick/webdev/ and edit the /etc/apache2/sites-enabled/site1 & /etc/apache2/sites-enabled/site2 files appropriately.

        Although as yet I haven't tested it from another machine, I'm guessing I will now be able to access it from http://192.168.1.82/site1 etc.

        Just thought I would post back in case any other users have been spending as much time trying to get that going as i have! LOL

        Thanks for the great tutorial. Feel free to edit this comment to keep it concise if you wish.

  16. Sumesh Gupta says:

    I have done exactly as you have described above and site1 and site2 are working absolutely wonderfully. I wish to know if I can create name base virtual hosts in apache with localhost and access them from same machine?
    (www.myname.com etc)
    I tried the process after reading a few howto's in ubuntu forums. However whenever I restart apache a warning is received that unnumbered virtual hosts and numbered virtual hosts port 80 are not supported and reloading fails. Can I get some help with this problem?

    • Linerd says:

      Sorry, I can't help you with that one. That's beyond the scope of anything I've tried to do. The Ubuntu Forums are probably a better place to find help for this. Good Luck.

  17. Paul says:

    Hey, Great Tutorial.

    I am attempting to setup a testing environment using unbuntu, however I am having some difficulties getting my site to work properly once placed into the var/www/ folder.

    It seems none of the relative paths work. In my index.php file for example, I have a bunch of includes and images, however none of them appear when I view the page, only the basic html text appears.

    I am assuming the most likely reason is that the file does not have read access to those files? Is this the case?

    Is there a quick terminal command to fix this if it is?
    Any help would be much appreciated.

    • Linerd says:

      I'm not sure what the correct permissions are. I'm thinking the files will need read and execute permission. To give everything read and execute permission, use this command.

      sudo chmod -R a+rx /var/www
  18. Squimpleton says:

    It worked the first day, but when I came back after, it didn't. I realized it was because the host file kept resetting to what it was before I saved it. So I re-edited it to add the various permissions.

    And now Site 1 and Site 2 are available, but for some reason they're accessing the files from my original localhost site. I checked the site1 and site2 config files and they still have home/myname/webdev/site1 and site2 as their documentroots and directories. So I don't get why they're pulling the files from localhost.

    Help?

  19. Mark says:

    Hi Linerd -

    Your tutorial worked beautifully for me - every step.

    Just reached the point where I downloaded the actual site and DB from my provider (for my first "test site") and the strangest thing is happening. I don't know what to make of it.

    + Before downloading the site files (pretty much a base installation of WordPress thus far) and DB - I would go to http://site1.com on my local machine and see the "Hello World" index.html that I wrote. Just fine.

    + After downloading (and configuring teh local database) - when I go to what I would expect to be the "local instance" of this site again (the non-www URL), it's automatically mapping to the "www" URL and taking me to the live site on the real web server. I validate this explicitly by pulling the network cable -- and wouldn't you know it... I get a connection timeout!!

    Do you have any idea why my local machine is now connecting to the [real] web server server when it didn't before? Is there something in my site that's making this mapping that I need to override? Any thoughts??

    Sorry if this is a noob question... but hey, I'm a noob!

    Any insights most appreciated. Thanks!

    Mark

    • Linerd says:

      So you downloaded the files from your provider rather than manually installing WordPress? The only thing I can figure is that there is a 301 redirect that's set up in one of the files from your provider's server. Take a look at this page: http://www.dailyblogtips.com/how-to-setup-a-301-redirect/

      The redirect will be either the one of the PHP methods or one of the Apache methods. ASP is for Microsoft servers. I'm betting it's an Apache redirect in your .htaccess file.

      If you can't find it, I suggest you blow away everything you downloaded and do a fresh local WordPress installation. http://tuxtweaks.com/2009/11/how-to-install-wordpress-on-ubuntu-part-1/

      I just work on my website theme locally and then upload the theme folder to my provider's server when I have things looking the way I want.

      One final thought. You said in your comment that you go to site1.com. You might want to try changing it to just site1.

      • Mark says:

        Thanks -

        Had only a little while to work this, but, I took your last comment and reworked my set-up so that mt local directories are truly site1, site2, etc... no longer site1.com, site2.com. That definely sounds better. It didn't resolve the problem yet, but it's cleaner.

        No obvious 301 redirects that weren't in the fresh WordPress download files. When I "grep 301 *" there were five php files with a 301 string - both my original WordPress and the new WordPress files matched on this front!

        Will try the fresh install via your other on-line links. We'll see how it goes...

        One question per another comment you made, though -

        So the core goal here is merely to modify my template, then? I'm trying to educate myself - and this clearly rings true. I have one site partially-functional (a small amount of initial content), but I do indeed want to significantly modify the template. If that's the case - I shouldn't be terribly worried about having my local content match as that's moot. It's all about the site design on the LAMP environment (and, naturally using as a repository for backups). Is that pretty much the philosophy?

        Thanks again!!

        Mark

        • Linerd says:

          Yeah, I just use the local LAMP setup for theme development and customizing. I don't really use it for backups of my site. My provider has a backup system available in Cpanel that will backup all of the site files and databases in one shot. Then I just download the archive to save it locally.

  20. amit says:

    great post.n Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>