Dev Notes

Software Development Resources by David Egan.

Apache Virtual Host Setup


Apache, Linux, Server, Sysadmin
David Egan

Apache Virtual Hosts allows multiple sites to be hosted on a single server/VPS.

These guidelines are for configuration of virtual hosts on Apache 2.4.

Create Directory Structure

sudo mkdir -p /var/www/html/example.com/public_html
sudo mkdir -p /var/www/html/example2.com/public_html

The -p flag creates intermediate directories as required.

Give permissions:

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

Note WordPress is going to need the www-data to have ownership of the public_html subdirectories to allow file upload etc. - for the time being, give ownership to the current user - pass ownership to www-data later.

Set Permissions to 755 for directories:

sudo chmod -R 755 /var/www

Add index.html demo pages if necessary.

Create Config Files

Create a config file for each site:

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

Use this as a template:

<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com
        ServerAdmin info@example.com
        DocumentRoot /var/www/html/example.com/public_html
        <Directory /var/www/html/example.com/public_html>
                Options -Indexes +FollowSymLinks
                AllowOverride All
                Require all granted
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/example.com.error.log
        CustomLog ${APACHE_LOG_DIR}/example.com.access.log combined
</VirtualHost>

This config block sets the correct server name, alias and document root. Directory browsing is disallowed, and .htaccess files are allowed.

Site specific error reporting is added - log files are located here:

/var/log/apache2/yoursite.com.error.log

Enable the site using a2ensiteand restart Apache:

sudo a2ensite yoursite.com.conf
sudo service apache2 restart

Enable Apache Rewrites

Enabling the Apache rewrite module will be essential it you’re using pretty permalinks. Enable the module & restart Apache:

sudo a2enmod rewrite && sudo service apache2 restart

or

sudo a2enmod rewrite && sudo /etc/init.d/apache2 restart

Set Up Permanent Redirect

Configure a new Virtual Host on the server to intercept requests for the old domain, and permanently redirect them to the new domain:

<VirtualHost *:80>
        ServerName olddomain-example.com
        ServerAlias www.olddomain-example.com
        ServerAdmin info@example.com

        Redirect 301 / http://new-example.com/

        ErrorLog ${APACHE_LOG_DIR}/olddomain-example.com.error.log
        CustomLog ${APACHE_LOG_DIR}/olddomain-example.com.access.log combined
</VirtualHost>

comments powered by Disqus