Virtualhosts in local environement

UPDATE: You can do all this steps in one command using Deven.

Sometimes a single local domain “localhost” is not enough if we develop more projects. Usually we just use folders for different projects, but woldn’t local domains be better? Some php scripts are not made to run from a subfolder and have problems with that. Here is the solution.

For this purpose I use the ‘local’ tld. I could use any existing or invented tld or even no tld at all and it would still work, but it’s good to be reminded that you’re on the local network.

So, how to achieve that http://myproject.local will point to your ~/public_html/myproject/ folder or wathever path you may chose for it?

First, edit your hosts file so that myproject.local will point to your local ip

sudo gedit /etc/hosts

add the line

127.0.1.1         myproject.local

If you open http://myproject.local and your apache is running, you will already see your localhost root, but that’s not what we want.

Now add a new virtualhost to apache. This could be a template

    ServerAdmin [email protected]
    ServerName myproject.local
    DocumentRoot /path/to/myproject
 
            
        Options FollowSymLinks
        AllowOverride None
    
    
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
       
 
    ErrorLog ${APACHE_LOG_DIR}/error.log    
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn 
    CustomLog ${APACHE_LOG_DIR}/access.log combined

On Debian based servers like Ubuntu just paste the above into a new file named myproject in /etc/apache2/sites-available and save. Of course you could put all kinds of other stuff in there, but this basic template should work just fine for a local installation.

Then do

 sudo /usr/sbin/a2ensite myproject

and check out if you have it in /etc/apache2/sites-enabled

If everything went well just do

sudo service apache2 reload

and that’s it. Your site should be visible as http://myproject.local

If you’re running something else than a Debian based machine the above works too. If sites-available and sites-enabled exist in the apache config directory but there’s no a2ensite facility,  just make a symlink of the file myproject to /etc/apache2/sites-enabled

ln -s /etc/apache2/sites-available/myproject /etc/apache2/sites-enabled/myproject

Else you may simply copy the virtualhost code into vhosts.conf or ultimately in httpd.conf

To restart apache on some systems, you will have to do:

/etc/init.d/apache2 restart

I think that covers it. Have fun!