Jan 19, 2015

Setting up virtual hosts for multiple domains in Apache

On my local Linux Mint system running Apache, the server root is at /var/www/html. Because I have multiple sites, each site is installed in a subdirectory under that root.

To browse to a site, I would use a url such as localhost/opti for the Optimizely module, which happens to be an instance of Drupal 8.

Lately, I've had problems with some site roots being subdirectories under the server root rather than being at the server root itself. So I figured it was time to learn how to set up virtual hosts.

The following steps worked for Linux Mint 17 with Apache 2.4.7.

(0)  Enabled the Apache module vhost_alias.

#  a2enmod  vhost_alias

(1)  Created a virtual host.

# cd  /etc/apache2/sites-available
# cp  000-default.conf  opti.conf


Edited opti.conf so that within the <VirtualHost *:80> directive, two changes were made.

Inserted the line for ServerName, where opti.local will be the url to use for the local site.

  ServerName  opti.local

Edited DocumentRoot to set the site root to its path.

  DocumentRoot  /var/www/html/opti


(2)  Enabled the site.

#  a2ensite  opti

(3)  Directed the new url to the local system.

Edited /etc/hosts to add  the following line.

127.0.0.1  opti.local

(4)  Restarted Apache.

#  service  apache2  restart

(5)  Browsed to opti.local instead of localhost/opti.

Caveat: after I set up the virtual host, I had problems with code that does matching of paths when I absent-mindedly went back to using the url localhost/opti. Although I haven't really explored this, there appears to be confusion that results from two different notions of what the base url is. If you've got a virtual host, it's best to use its url consistently.

(Many thanks to Darren Lee for mentioning Apache's virtual hosts to me.)

Sources:

Setting Up Virtual Hosts for Apache on Ubuntu for Local Development
http://blog.code4hire.com/2011/03/setting-up-virtual-hosts-for-apache-on-ubuntu-for-local-development/

How To Set Up Apache Virtual Hosts on Ubuntu 12.04 LTS
https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts

2 comments:

  1. Here is very informative article about configuring apache virtual host on RHEL or CentOS.
    http://www.sysadminshowto.com/configure-ip-based-apache-virtual-host-rhel-6-x-centos-6-x/

    ReplyDelete