Serving a content out of directory other than the DocumentRoot directory with Apache2

This config will show a basic example on how to server a content out of directory other that the DocumentRoot directory using Apache2 web server. Let’s begin with a simple virtual host configuration.

<VirtualHost *:80>

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

<VirtualHost>

The above VirtualHost configuration will serve a content form the DocumentRoot directory. Let’s create some basic page to confirm our settings:

# echo "Serving content from /var/www/html" > /var/www/html/index.html

By accessing out web server available we get a following content:

$ curl http://localhost/
Serving content from /var/www/html

The given html document has been loaded from the DocumentRoot directory /var/www/html.

If we want to also serve a content from other directory then the DocumentRoot directory /var/www/html we can create an additional alias. Here is the new VirtualHost configuration file which apart of /var/www/html will also serve a content from /opt/www/ using an URL alias suffix /opt/

<VirtualHost *:80>

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        Alias   "/opt/" "/opt/www/"

        <Directory "/opt/www/">
                Require all granted
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

<VirtualHost>

Save your new config and reload apache web server:

# service apache2 reload
[ ok ] Reloading web server: apache2.

Next, create a simple page within /opt/www/ alias directory:

# echo "Serving content from /opt/www/" > /opt/www/index.html

Accessing our web server using an alias URL suffix /opt/ will serve a content from /opt/www directory:

$ curl http://localhost/opt/
Serving content from /opt/www/

Troubleshooting

The 404 Not Found usually means that you are trying to access a non existing content or you have provided an incorrect URL. Watch out for a trailing / in your URL as http://localhost/opt and http://localhost/opt/ are two distinct URLs. If you do not wish your URL to include trailing / character you need to remove both trailing / characters from the above Alias directive of your VirtualHost configuration.


The AH01630: client denied by server configuration error log indicates denied access due to incorrectly configured access control. For versions of Apache web server below 2.4 you may need to change your access control to:

        <Directory "/opt/www/">
                Order allow,deny
                Allow from all
        </Directory>